<?php
include("connection.php");
include("frames_header.php");
?>

<?php
if (isset($_POST["speciesaniseed"]))
{
	$speciesaniseed=$_POST["speciesaniseed"];
  //echo "species aniseed : $speciesaniseed";
}
else 
{
 echo "<h2>Error: Please select a species.</h2>";
 include("frames_footer.php");
 return;
}

$pathtowrite="./updates/inparanoid/inparanoidlog.txt";
if(!($fdwrite=fopen ($pathtowrite, "w")))
{
	//echo" ERROR : Can't create the file :$pathtowrite <BR>";
	include("frames_footer.php");
	return;
}
else
{
	echo " The file : $pathtowrite is created<BR>";
}
$ligne = date("j, n, Y, H:i:s")."\n";
fputs($fdwrite,$ligne);



//to uncompress the Ensmart results file
function uncompress($fromFile, $toFile) 
{
   $zp = @gzopen($fromFile, "r");
   $fp = @fopen($toFile, "w");
   while(!@gzeof($zp)) {$string = @gzread($zp, 4096); @fwrite($fp, $string, strlen($string));}
   @gzclose($zp);
   @fclose($fp);
}


$species=$_POST["species"];
//echo "species = $species<br>";



if (isset($_POST["updatebioname"]))
	$bioname=$_POST["updatebioname"];
else $bioname='n';

if (isset($_POST["updateorto"]))
	$orto=$_POST["updateorto"];
else $orto='n';

if (isset($_POST["updatepara"]))
	$para=$_POST["updatepara"];
else $para='n';

if (isset($_POST["updatego"]))
	$upgo=$_POST["updatego"];
else $upgo='n';


if (isset($_POST["test"]))
	$test=$_POST["test"];
else $test='n';
if($test=='y'){
	print "Test mode selected. No data will be recorded.<br>";
}//else print "No test mode selected. Data will be recorded.<br>";



// $path is the filepath of the inparanoid results file
if (isset($_POST["filepath"]))
	$path=$_POST["filepath"];
else $path="";

if($path=="")
{
	echo"Error: please select an Inparanoid results file<BR>";
	include("frames_footer.php");
	return;
}
echo "The Inparanoid file is : $path<br>";


// $pathmart is the filepath of the Ensmart results file
if (isset($_POST["fileEnsmart"]))
	$pathmart=$_POST["fileEnsmart"];
else $pathmart="";

if($pathmart=="")
{
	echo"Error: Please select an Ensmart file<BR>";
	include("frames_footer.php");
	return;
}

//verify is the user enter a good .gz file. If yes uncompress this file
if (ereg("(.+)\.gz$", $pathmart,$tab))
{

	$fnametmp=$tab[1];
	
	/*$tmp=split('[\]',$fnametmp); // Semble etre une erreur dans le sens du slash dans ce sens pour Windows*/
	$tmp=split('[/]',$fnametmp); /* dans ce sens pour linux*/
//	print_r($tmp);	
	$fname=end($tmp);
//	echo"file : $fname<br>";
	$fdest="./updates/inparanoid/".$fname;
//	echo "<br>fdest::$fdest<br>";




	uncompress($pathmart, $fdest);
	
	if(filesize($fdest)<=0) // test if uncompress is OK
	{
		echo "Bad uncompressed GZ file<br>";
		include("frames_footer.php");
		return;
	}
	else
	{
		echo "The .gz file is uncompressed<br>";
	}
}


// open the different file needed 
if(!($fdciorg=fopen ($path, "r")))
{
	echo" ERROR : Can't open the file :$path <BR>";
	include("frames_footer.php");
	return;
}/*
else
{
	echo" The file to parse : $path is open <BR>";
}
*/
if(!($fdensmart=fopen ($fdest, "r")))
{
	echo" ERROR : Can't open the file :$fdest <BR>";
	//echo" ERROR : You didn't have put a .gz file in the filepath <BR>";
	include("frames_footer.php");
	return;
}
else
{
	echo" The file $fdest is open <BR>";
}

//the go file for the different species
switch($species)
{
	case "Homo sapiens" :
		$fgoa="./updates/goa/gene_association.goa_human";
		break;
	case "Mus musculus" :
		$fgoa="./updates/goa/gene_association.goa_mouse";
		break;
	case "Drosophila melanogaster" :
		$fgoa="./updates/goa/gene_association.fb";
		break;
}

// open the go file
if(!($fdgoa=fopen ($fgoa, "r")))
{
	echo" ERROR : Can't open $fgoa <BR>";
	include("frames_footer.php");
	return;
}
else
{
	echo" The file $fgoa is open <BR>";
}


//creating the associated tab with the good field of the Ensmart File

//Pour parcourir le tableau par champs disponibles dans le fichier ensmart

// looking for all the fields needed in the Ensmart file for the species orthologs
$bufferensmart = fgets($fdensmart, 4096);
$bufferensmart=trim($bufferensmart);
$tmp=split("\t",$bufferensmart);
if (!(in_array("Description",$tmp))&&($species!="Drosophila melanogaster"))
{
	echo "Description not found in your EnsMart Results file <br>";
}

if (!(in_array("Ensembl Peptide ID",$tmp)))
{
	echo "Ensembl Peptide ID not found in your EnsMart Results file <br>";
}
if (!(in_array("UniProt/Swiss-Prot ID",$tmp)))
{
	echo "UniProt/Swiss-Prot ID not found in your EnsMart Results file <br>";
}
if ((!(in_array("HUGO ID",$tmp))) && ($species=="Homo sapiens"))
{
	echo "HUGO ID not found in your EnsMart Results file for $species <br>";
}
if ((!(in_array("UniProt/TrEMBL ID",$tmp)))&& ($species=="Homo sapiens"))
{
	echo "UniProt/TrEMBL ID not found in your EnsMart Results file for $species <br>";
}

if ((!(in_array("FlyBase Gene ID",$tmp)))&& ($species=="Drosophila melanogaster"))
{
	echo "FlyBase Gene ID not found in your EnsMart Results file for $species <br>";
}
if ((!(in_array("FlyBase Symbol ID",$tmp)))&& ($species=="Drosophila melanogaster"))
{
	echo "FlyBase Symbol ID not found in your EnsMart Results file for $species<br>";
}
if (!(in_array("Family Description",$tmp)))
{
	echo "Family Description not found in your EnsMart Results file <br>";
}
for($i=0; $i<count($tmp); $i++)
{
	$kv[$tmp[$i]]=$i;
}



// reading the ensmart File and creating the index for this file
while(!feof($fdensmart))
{	
	// using pointeur
	$pointeur=ftell ( $fdensmart);
	$bufferensmart = fgets($fdensmart, 4096);
	$tmpensmart=split("\t",$bufferensmart);
	if(ereg("^([A-Za-z0-9\-]+)",$tmpensmart[$kv["Ensembl Peptide ID"]],$tmpid))
	{
		$id=$tmpid[1];
	}
	if (isset($tabensmart[$id]))
	{
		$tabensmart[$id]=$tabensmart[$id]."*".$pointeur;
	}
	else
	{
		$tabensmart[$id]=$pointeur;
	}
}


// reading the goa file and creating the index tab for this file
while(!feof($fdgoa))
{	
	$pointeurgoa1=ftell ($fdgoa);
	$buffergoa = fgets($fdgoa, 4096);
	$tmpgoa=split("\t",$buffergoa);
	$id1=$tmpgoa[1];
	$id2=$tmpgoa[2];
	if(($id1!="")&&($id2!=""))
	{
		if (isset($tabgoaid1[$id1])) 
		{	
			$tabgoaid1[$id1]=$tabgoaid1[$id1]."*".$pointeurgoa1;
		}
		else
		{
			$tabgoaid1[$id1]=$pointeurgoa1;
		}
		if (isset($tabgoaid2[$id2]))
		{	
			$tabgoaid2[$id2]=$tabgoaid2[$id2]."*".$pointeurgoa1;
		}
		else
		{
			$tabgoaid2[$id2]=$pointeurgoa1;
		}
	}
	
}

//deleting the biological names
if ($bioname=='y')
{


	$requete= "DELETE from \"SYNO\" where \"ORIGIN_SPECIES\" ='$species'and \"GENE_ID\" in (select \"MOL_ID\" from \"MOL_ENTITY\" where \"SPECIES\"='$speciesaniseed' )";
	//if($test=='y')
	//{
		echo " All biological names infered to $speciesaniseed from $species will be erased <br>";
		//echo " REQUETE =$requete <br>";
	//}
	if ($test=='n')
	{
		pg_query($c,"begin");
		$stmt0 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
		pg_query($c,"commit");
		//ocifreestatement($stmt0);	
	}
		
}



// deleting all the go for the ortholog species
if ($upgo=='y')
{
	$requete= "DELETE from \"GO_DESCRIPTION\" where \"SPECIES_ORIGIN\" ='$species' AND \"PHYLOGENY_ORIGIN\"='y' AND \"IP_ORIGIN\" is NULL AND \"BLAST_ORIGIN\" is NULL and \"MOL_ID\" in (select \"MOL_ID\" from \"MOL_ENTITY\" where \"SPECIES\"='$speciesaniseed')";
	//if($test=='y')
	//{
		echo " All the corresponding GO will be erased <br>";
	//	echo " REQUETE =$requete <br>";
	//}
	if ($test=='n')
	{
		pg_query($c,"begin");
		$stmt01 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
		pg_query($c,"commit");		

		//ocifreestatement($stmt01);	
	}
	$requete= "Update \"GO_DESCRIPTION\" set \"PHYLOGENY_ORIGIN\"='' where \"SPECIES_ORIGIN\" ='$species'";
	/*
	if($test=='y')
	{
		echo " REQUETE Update =$requete <br>";
	}*/
	if ($test=='n')
	{
		pg_query($c,"begin");
		$stmt02 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
		pg_query($c,"commit");

		//ocifreestatement($stmt02);	
	}
}
// delete of all the paralogs for ciona	
if ($para=='y')
{
	$requete= "DELETE from \"PHYLOGENY\" where \"PARALOG\" is not NULL and \"SPECIES\" ='$speciesaniseed'";
	//if($test=='y')
	//{
		echo " All the corresponding paralogs will be erased <br>";
		//echo " REQUETE =$requete <br>";
	//}
	if ($test=='n')
	{
		pg_query($c,"begin");
		$stmt03 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
		pg_query($c,"commit");

		//ocifreestatement($stmt03);	
	}

}


// delete all the orto corresponding to this species
if ($orto=='y')
{
	$requete= "DELETE from \"PHYLOGENY\" where \"SPECIES\" ='$species'";
	//if($test=='y')
	//{
		echo " All the coresponding paralogs will be erased <br>";
		//echo " REQUETE =$requete <br>";
	//}
	if ($test=='n')
	{
		pg_query($c,"begin");
		$stmt04 = pg_query($c, $requete) or die("<strong>Error</strong> ".pg_last_error($c));
		pg_query($c,"commit");		

		//ocifreestatement($stmt04);	
	}

}
$cptnotinensmart=0;  // to know how much id are not in the ensmart file
$gonotindb=0; 
$c2=0;
$bufferciorg = fgets($fdciorg, 4096);
//for($x=0; $x<100; $x++)
while(!feof($fdciorg))
{
	$c2++;
	if($c2==100)  // to write the hour in the log file
	{
		$ligne = date("H:i:s")."\n";
		fputs($fdwrite,$ligne);
		$c2=0;
	}
	
	$foundgo=0;
	$indgo=0;
	$tabgo=array(null);
	$bufferciorg = fgets($fdciorg, 4096);
	$tab=array(null);
	$tab=split("\t",$bufferciorg);
	echo "<br>--------------$tab[0]--------------<br>";
	$ligne = "\n--------------".$tab[0]."--------------\n";
	fputs($fdwrite,$ligne);
	$score=$tab[1];
	$ci=array(null);
	$or=array(null);
	
	// reading the first and second IDs
  $ci=split(" ",trim($tab[2]));
	$or=split(" ",trim($tab[3]));
	
	// size of the different tab id
	$sizeci=count($ci);
	$sizeor=count($or)/2;
	echo"<br>ci =";
	print_r($ci);
	echo"<br>or =";
	print_r($or);
	echo"<br>";
	
	// for each ci without the score...
	for($a=0; $a<$sizeci; $a+=2)
	{
		for($b=0; $b<$sizeci; $b+=2)
		{
			if($a!=$b)
			{
			// to put the paralog of the current ci
				$requete="SELECT \"MOL_ID\" FROM \"PHYLOGENY\" where \"PARALOG\"='$ci[$b]' and \"MOL_ID\"=(select \"GENE_ID\" from \"GENE\" where \"NAME\"='$ci[$a]')";	
				$stmt = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
				if(!$row=pg_fetch_array($stmt))
				{
					if(($test=='n')&&($para=='y'))
					{
						$requete = "INSERT INTO \"PHYLOGENY\" (\"MOL_ID\", \"PARALOG\", \"SCORE\", \"SCORE1\", \"SCORE2\", \"SPECIES\" ) values ( (select \"GENE_ID\" from \"GENE\" where \"NAME\"='$ci[$a]'),'$ci[$b]', $score, ".($ci[$a+1]*100).",".($ci[$b+1]*100).",'$speciesaniseed')";
						
						pg_query($c,"begin");
						$stmt2 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
						pg_query($c,"commit");

						//ocifreestatement($stmt2);
					}
					// in test mode
					/*
					if(($test=='y')&&($para=='y'))
					{
						echo "(fake)INSERT INTO ciona_design.phylogeny (mol_id, paralog, score, score1, score2, species ) values ( (select gene_id from ciona_design.gene where name='$ci[$a]'), '$ci[$b]', $score, ".($ci[$a+1]*100).",".($ci[$b+1]*100).",'$speciesaniseed')<br>";
					}*/
					
				}
				else 
				{
					echo "Duplicate paralog entry <br>";
				}
				echo "----> $ci[$a] (".($ci[$a+1]*100).") paralog of $ci[$b] (".($ci[$b+1]*100).")<br>";
				
				//ocifreestatement($stmt);
			}
			
		}
	}
	for($y=0; $y<count($or) ; $y+=2 )
	{
		$a=0;
		$name=array(null); // array containing all the possible name for this ortolog
		$tabinfo=array(null); // the tab containing all the informations fom the ensmart file ....
		$indinfo=0; // current indice for the tabinfo array
		if(array_key_exists($or[$y],$tabensmart))
		{
			$w=$y;
			//echo" tabensmart[$or[$y]] trouve<br>";
			//echo " tabensmart pour $or[$y] = ".$tabensmart[$or[$y]]."<br>";
			$tabpointeur=split("\*",$tabensmart[$or[$y]]);
			print_r($tabpointeur);
			
			
			for($index=0;$index<count($tabpointeur); $index++)
			{
				$princname=""; // the principal name for the current ortolog
				fseek($fdensmart,$tabpointeur[$index]);
				$bufferensmart=fgets($fdensmart, 4096);
				$tmpensmart=split("\t", $bufferensmart);
				echo"<br>tmpensmart:";
				print_r($tmpensmart);
				echo"<br>";
				
				
				// getting all the informations needed
				if( isset($kv["Ensembl Peptide ID"]))
				{
					if(ereg("^([A-Za-z0-9]+)",$tmpensmart[$kv["Ensembl Peptide ID"]],$tens))
					{
						$tabinfo[$indinfo]=trim($tens[1]);
						$indinfo++;
						$ensinfo=trim($tens[1]);
						
					}
					echo"<br>ensinfo==$ensinfo<br>";
				}
				if( isset($kv["UniProt/Swiss-Prot ID"]))
				{
				 // get only the first part(TOTO) of the UniProt/Swiss-Prot ID  ex : TOTO_Human
					if(ereg("(.+)_.+$",$tmpensmart[$kv["UniProt/Swiss-Prot ID"]],$tswp))
					{
						$tabinfo[$indinfo]=trim($tmpensmart[$kv["UniProt/Swiss-Prot ID"]]);
						$indinfo++;
						$name[$a]=$tswp[1];
						$a++;
					}
				}
				if( isset($kv["HUGO ID"]))
				{
					$tabinfo[$indinfo]=trim($tmpensmart[$kv["HUGO ID"]]);
					$indinfo++;
					$name[$a]=$tmpensmart[$kv["HUGO ID"]];
					$a++;
				}
				if( isset($kv["UniProt/TrEMBL ID"]))
				{
					$tabinfo[$indinfo]=trim($tmpensmart[$kv["UniProt/TrEMBL ID"]]);
					$indinfo++;
				}
				if( isset($kv["FlyBase Gene ID"]))
				{
					$tabinfo[$indinfo]=str_replace("'", "\"",trim($tmpensmart[$kv["FlyBase Gene ID"]]));
					$indinfo++;
				}
				if( isset($kv["FlyBase Symbol ID"]))
				{
					$tabinfo[$indinfo]=str_replace("'", "\"",trim($tmpensmart[$kv["FlyBase Symbol ID"]]));
					$indinfo++;
					if (!ereg("^CG", $tmpensmart[$kv["FlyBase Symbol ID"]]))
					{
					 	 $name[$a]=str_replace("'", "\"",trim($tmpensmart[$kv["FlyBase Symbol ID"]]));
						 $a++;
				  }
				}
				if( isset($kv["Family Description"]))
				{
					$family=str_replace("'", "\"",trim($tmpensmart[$kv["Family Description"]]));
				}
				if( isset($kv["Description"]))
				{
//				echo"<br> @@@@@@@@@@@@@@@@@ description ====".$tmpensmart[$kv["Description"]];
					if(ereg("^(.+)\.\ \[Source\:.+\]$",$tmpensmart[$kv["Description"]],$tdescrip))
					{
						$description=str_replace("'", "\"",trim($tdescrip[1]));
						//$description=str_replace(";", "", $description);
						$name[$a]=$description;
						$a++;
					}
					
				}
				
				// to give the best principal name to the ortolog
				if(strlen($princname)<=0 )
				{
					if (strlen($tmpensmart[$kv["UniProt/Swiss-Prot ID"]])!=0)
					{
						if(ereg("(.+)_.+$",$tmpensmart[$kv["UniProt/Swiss-Prot ID"]],$tmpname))
							$princname=str_replace("'", "\"", $tmpname[1]);
						else $princname=str_replace("'", "\"", $tmpensmart[$kv["UniProt/Swiss-Prot ID"]]);
					}
					elseif (strlen($tmpensmart[$kv["HUGO ID"]])!=0)
						$princname=str_replace("'", "\"",trim($tmpensmart[$kv["HUGO ID"]]));
					elseif(strlen($tmpensmart[$kv["FlyBase Symbol ID"]])!=0)
						$princname=str_replace("'", "\"",trim($tmpensmart[$kv["FlyBase Symbol ID"]]));
	                        //elseif(strlen($tmpensmart[$kv["UniProt/TrEMBL ID"]])!=0)
						//$princname=str_replace("'", "\"",trim($tmpensmart[$kv["UniProt/TrEMBL ID"]]));
					elseif(strlen($tmpensmart[$kv["Ensembl Peptide ID"]])!=0)
						$princname=str_replace("'", "\"",$ensinfo);
					else
						echo "No name for : ".$or[$y]."<br>";
				}
				echo"<br>tabinfo=";
				print_r($tabinfo);
				echo"<br>name=";
				print_r($name);
				echo"<br>";
				echo"princname=$princname";
				
				for($a=0;$a<$sizeci;$a+=2)
				{
					$requete= "SELECT \"MOL_ID\" FROM \"PHYLOGENY\" where \"ID\"='$or[$y]' and \"MOL_ID\"=(select \"GENE_ID\" from \"GENE\" where \"NAME\"='$ci[$a]')";
					$stmt3 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
					if(!$row3=pg_fetch_array($stmt3))
					{
						$requete= "INSERT INTO \"PHYLOGENY\" (\"MOL_ID\", \"ORTHOLOG\", \"ID\", \"DB\", \"SCORE\", \"SCORE1\", \"SCORE2\", \"SPECIES\") values ( (select \"GENE_ID\" from \"GENE\" where \"NAME\"='$ci[$a]'), '$princname', '$or[$y]', 'ensembl', $score, ".($ci[$a+1]*100).",".($or[$w+1]*100).", '$species' )"; 
						/*
						if(($test=='y')&&($orto=='y'))
						{
							echo "<br> REQUETE2 == $requete <br>" ;
						}*/
						if(($test=='n')&&($orto=='y'))
						{
							pg_query($c,"begin");
							$stmt4 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
							pg_query($c,"commit");

							//ocifreestatement($stmt4);
						}
					}
					else
					{
						//echo " Duplicate ortholog entry <br>";
					}
					//ocifreestatement($stmt3);
					
					// Synonyms for this ortolog
					if($bioname=='y')
					{
						if ((($or[$y]!=$princname) && (!ereg($princname,$or[$y]))) || $tmpensmart[$kv["Description"]]!="" )
						{
							for($i=0; $i<count($name); $i++)
							{
								if(strlen($name[$i])!=0)
								{
								// using the rules of Olivier to make a better search
								// each letter in upper case ... a blank beetween a letter and a number ...replace ilegal caracter with a blank
									$namecur=$name[$i];
									$name2=strtoupper($namecur);
									$name2=preg_replace('([^a-z A-Z 0-9])',' ', $name2);
									$name2=ereg_replace("([a-zA-Z])([0-9])","\\1 \\2",$name2);
									$name2=ereg_replace("([0-9])([a-zA-Z])","\\1 \\2",$name2);
									$name2=preg_replace('/\ +/',' ',$name2);
									$name2=trim($name2);
									$requete= "SELECT \"SYNO_UPPER_CASE\" FROM \"SYNO\" where \"SYNO_UPPER_CASE\"='$name2' and \"GENE_ID\"=(select \"GENE_ID\" from \"GENE\" where \"NAME\"='$ci[$a]')";
									//echo"REQUETE3= $requete <br>";
									$stmt5 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
									if(!$row5=pg_fetch_array($stmt5))
									{
										$requete= "INSERT INTO \"SYNO\" (\"GENE_ID\", \"SYNO\", \"ORIGIN\", \"SYNO_UPPER_CASE\", \"ORIGIN_SPECIES\") values ( (select \"GENE_ID\" from \"GENE\" where \"NAME\"='$ci[$a]'), '$namecur', 'phylogeny', '$name2', '$species' )"; 
										/*
										if($test=='y')
										{
											echo "<br> REQUETE4 == $requete <br>" ;
										}*/
										if($test=='n')
										{
											pg_query($c,"begin");
											$stmt6 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
											pg_query($c,"commit");

											//ocifreestatement($stmt6);
										}
									}
									else
									{
									//echo " Duplicate synonym entry <br>";
									}
									//ocifreestatement($stmt5);
								}
							}
						}
						else 
                                    {
                                          echo " <br> or= $or[$y] princname=$princname <br>";
                                    }
					}
					
					// adding the information : protein family
					if (($orto=='y'))
					{
				 
						$requete="update \"PHYLOGENY\" set \"FAMILLY\"='$family' where \"MOL_ID\"=(select \"GENE_ID\" from \"GENE\" where \"NAME\"='$ci[$a]') and \"ID\"='$or[$y]' and \"SPECIES\"='$species'"; #/// 
						/*
						if($test=='y')
						{
							echo "<br> REQUETE Update == $requete <br>" ;
						}*/
						if($test=='n')
						{
							pg_query($c,"begin");
							$stmt7 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
							pg_query($c,"commit");

							//ocifreestatement($stmt7);
						}
					}
				}
				
			}
		}
		else
		{
			$cptnotinensmart++;
			echo"** Peptide $or[$y] not found in the ENSMART file.<br>";
		}
		
		// adding GO informations
		if ($upgo=='y')
		{	
			
			for($i=0; $i<count($tabinfo); $i++)
			{
				if($tabinfo[$i]!="")
				{
					if(array_key_exists($tabinfo[$i],$tabgoaid1))
					{
						$foundgo=1;
						$tmpgo=split("\*",$tabgoaid1[$tabinfo[$i]]);
						for($k1=0;$k1<count($tmpgo); $k1++)
						{
							fseek($fdgoa,$tmpgo[$k1]);
							$buffergoa=fgets($fdgoa, 4096);
							$tmpinfogoa=split("\t", $buffergoa);
							for($j=0;$j<count($tmpinfogoa);$j++)
							{
								if (ereg("^GO\:([0-9]+)",$tmpinfogoa[$j],$gotab))
								{
									
									$go="GO:".$gotab[1];
									//echo"GO1 : $go ";
									if(!in_array($go,$tabgo))
									{
										$tabgo[$indgo]=$go;
										$indgo++;
									}
								}
							}
						}
					}
					if(array_key_exists($tabinfo[$i],$tabgoaid2))
					{
						$foundgo=1;
						$tmpgo=split("\*",$tabgoaid2[$tabinfo[$i]]);
						for($k2=0;$k2<count($tmpgo); $k2++)
						{
							fseek($fdgoa,$tmpgo[$k2]);
							$buffergoa=fgets($fdgoa, 4096);
							$tmpinfogoa=split("\t", $buffergoa);
							for($j=0;$j<count($tmpinfogoa);$j++)
							{
								if (ereg("^GO\:([0-9]+)",$tmpinfogoa[$j],$gotab))
								{
									
									$go="GO:".$gotab[1];
									//echo"GO2 : $go ";
									if(!in_array($go,$tabgo))
									{
										$tabgo[$indgo]=$go;
										$indgo++;
									}
									
								}
							}
						}
					}
				}
				
			}
			//echo"<br>tabgo:::::";
			print_r($tabgo);
		}
	}
	
	if ($foundgo!=1)
	{
		echo "GO NOT FOUND FOR THIS PEPTIDE<br>";
	}
	else
	{
		
		for($a=0;$a<$sizeci;$a+=2)
		{
			for($i=0;$i<count($tabgo);$i++)
			{
				$requete="select * from \"GO\" where \"GO_ID\"='$tabgo[$i]'";
				$stmt7a = pg_query($c,$requete);
				if($row7a=pg_fetch_array($stmt7a))
				{
					$requete= "SELECT \"MOL_ID\" FROM \"GO_DESCRIPTION\" where \"GO_ID\"='$tabgo[$i]' and \"MOL_ID\"=(select \"GENE_ID\" from \"GENE\" where \"NAME\"='$ci[$a]')";
					$stmt7b = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
					if(!$row7b=pg_fetch_array($stmt7b))
					{
						$requete= "INSERT INTO \"GO_DESCRIPTION\" (\"MOL_ID\", \"GO_ID\", \"ORIGIN\", \"SPECIES_ORIGIN\",\"PHYLOGENY_ORIGIN\") values ( (select \"GENE_ID\" from \"GENE\" where \"NAME\"='$ci[$a]'), '$tabgo[$i]', 'phylogeny', '$species','y' )"; 
						/*
						if($test=='y')
						{
							echo "<br> REQUETE6 == $requete <br>" ;
						}*/
						if($test=='n')
						{
							//echo"requete GO = $requete";
							pg_query($c,"begin");
							$stmt8 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
							pg_query($c,"commit");							

							//ocifreestatement($stmt8);
						}
					}
					else
					{
						//ocifreestatement($stmt7b);
						$requete=" update \"GO_DESCRIPTION\" set \"PHYLOGENY_ORIGIN\"='y', \"SPECIES_ORIGIN\"='$species' where \"GO_ID\"='$tabgo[$i]' and \"MOL_ID\"=(select \"GENE_ID\" from \"GENE\" where \"NAME\"='$ci[$a]')";
						/*
						if($test=='y')
						{
							echo "<br> REQUETE7 == $requete <br>" ;
						}*/
						if($test=='n')
						{
							pg_query($c,"begin");
							$stmt9 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
							pg_query($c,"commit");
							//ocifreestatement($stmt9);
						}
						
					}
				}
				else
				{
					$gonotindb++;
				}
				//ocifreestatement($stmt7a);
			}
		}
	}
}
	
	

echo" GO not inserted in the ANISEED db=  ".$gonotindb. "<br>";
echo" Orthologs not found in the ENSMART file=  ".$cptnotinensmart. "<br>";
//echo"<br>tabensmart <br>";
//print_r($tabensmart);
//fclose($fdensmart);

fclose($fdciorg);
fclose($fdensmart);
fclose($fdgoa);



?>
<?php
    include("frames_footer.php");
?>