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


<?php

if (isset($_POST["test"]))
{
	$test=$_POST["test"];
	
}
else $test="n";

if (isset($_POST["filepath"]))
{
	$path=$_POST["filepath"];
	$path = str_replace('"','',$path);
}
else $path="";

if (isset($_POST["species"]))
{
	$species=$_POST["species"];
}
else
{
	echo "<H3>ERROR : missing parameter: species</H3>";
	include ("frames_footer.php");
	return;
}


$pathtowrite="./updates/addgeneslog.txt";
if(!($fdwrite=fopen ($pathtowrite, "w")))
{
	//echo" ERROR : Can't create the file :$pathtowrite <BR>";
	include("frames_footer.php");
	return;
}
else
{
	echo " file $pathtowrite created<BR>";
}


if ($path!="")
{
	if(!($fdread=fopen($path, "r")))
	{
		echo " ERROR : Can't open the file :$path <BR>";
		include("frames_footer.php");
		return;
	}
	else
	{
		echo " The file to read : $path is open <BR>";
		
		$buffer = fgets($fdread, 4096);
		
		
		$cpt=1;
		$cptupdategenes=0;
		$cptnewgenes=0;
		$seq="";
		while(!feof($fdread))
		{
			//Cas d'une ligne vide
			if ($buffer=="\n") {$buffer = fgets($fdread, 4096);continue;}

			if ( ereg("^>(.+)", $buffer, $tabinfo))
			{
			
				$ligne="----$cpt----";
				echo"$ligne <br>";
				$name=trim($tabinfo[1]);
				//print_r($tabinfo);
				echo "<br>NAME= $name <br>";
				$buffer = fgets($fdread, 4096);
				
				$cpt++;
				fputs($fdwrite,$ligne."\n");
				fputs($fdwrite,"NAME=".$name."\n");
				
			} 
			else
			{
			
				while ( !ereg("^>", $buffer) && (!ereg("^\n",$buffer)) && (!feof($fdread)) )
				{	
				//print "encorela";
					$seq=$seq.$buffer;
					$buffer = fgets($fdread, 4096);
					
				
				}
			print $seq;
			
				$seq=trim($seq);
				$seq=strtoupper($seq);
				echo "$seq <br>";
				fputs($fdwrite,$seq);
				$freqA=substr_count($seq, "A"); 
				//echo "<br>freq A = $freqA";
				$freqG=substr_count($seq, "G"); 
				//echo "<br>freq G  = $freqG";
				$freqC=substr_count($seq, "C"); 
				//echo "<br>freq C = $freqC";
				$freqT=substr_count($seq, "T"); 
				//echo "<br>freq T = $freqT";
			
				$freqtot= $freqA+$freqC+$freqG+$freqT;
			
				$seq2=ereg_replace("[^[:alpha:]]","",$seq);
				$size=strlen($seq2);
				$freqother=$size-$freqtot;
				//echo "<br>freq OTHER = $freqother";
				//echo "<br>size= $size<br>";
				
				$seqcomments="BASE COUNT ".$freqA." A  ".$freqC." C  ".$freqG." G  ".$freqT." T  ".$freqother." OTHERS\n";
			    echo "<br>$seqcomments<br>size= $size<br>";
				fputs($fdwrite,"\n STATS SEQ===$seqcomments // size= $size \n");
				
				if ($name!="")
				{
					$requete="select \"GENE_ID\" from \"GENE\" where \"NAME\"='$name'";
					$stmt0 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
					//echo "REQUETE=$requete";
					if(!$row0=pg_fetch_array($stmt0))
					{

						$cptnewgenes++;
						// THE CURRENT GENE NOT exists the system will create it into aniseed (CREATE THE BIO_ENTITY, THE MOL_ENTITY AND THE GENE)!! 
						$requete="INSERT INTO \"BIO_ENTITY\" (\"BIO_ID\", \"CURATED\" ) values ( nextval('\"S_BIO_ID\"'),'y')";
						//echo "requete=$requete<br>";
						if ($test=="n")
						{
						
						pg_query($c,"begin");
							$stmt1= pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
							
						}
						else 
						    //echo "<br>GENE not found in ANISEED : (fake1 ---->table bio_entity) $requete<br>";
							print "-";
						
						
						$requete="INSERT INTO \"MOL_ENTITY\" (\"MOL_ID\", \"SPECIES\", \"NAME\", \"TYPE\" ) values (currval('\"S_BIO_ID\"'),'$species', '$name', 'gene')";
						//echo "requete=$requete<br>";
						if ($test=="n")
						{
							$stmt1= pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
							
						}
						else 
							//echo "<br>GENE not found in ANISEED : (fake2 ---->table mol_entity) $requete<br>";
							print "-";
						
						
						$requete="INSERT INTO \"GENE\" (\"GENE_ID\", \"NAME\") values (currval('\"S_BIO_ID\"'), '$name')";
						//echo "requete=$requete<br>";
						if ($test=="n")
						{
							$stmt1= pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
							
						}
						else 
							//echo "<br>GENE not found in ANISEED : (fake3 ---->table gene) $requete<br>";
							print "-";
						
						
						
						$namemodif=strtoupper($name);
						$namemodif=ereg_replace("[^a-zA-Z0-9]"," ",$namemodif);
						$namemodif=ereg_replace("([a-zA-Z])([0-9])","\\1 \\2",$namemodif);
						$namemodif=ereg_replace("([0-9])([a-zA-Z])","\\1 \\2",$namemodif);
						$namemodif=ereg_replace(" +"," ",$namemodif);
						$namemodif=ereg_replace("^ ","",$namemodif);
						$namemodif=ereg_replace(" $","",$namemodif);
						$requete="INSERT INTO \"SYNO\" (\"GENE_ID\", \"SYNO\", \"SYNO_UPPER_CASE\") values (currval('\"S_BIO_ID\"'), '$name', '$namemodif')";
						//echo "requete=$requete<br>";
						if ($test=="n")
						{
							$stmt1= pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
							
						}
						else 
							print "-";
						
						
						if ($test=="n")
						{
						$oid=pg_lo_create($c); 
						$requete="INSERT into \"SEQUENCE\" (\"MOL_ID\", \"SEQUENCE\", \"LENGTH\", \"COMMENTS\") values (currval('\"S_BIO_ID\"'),'$oid','$size','$seqcomments')";
						$result=pg_query($c, $requete) or die("<strong>Error</strong> ".pg_last_error($c));
						$handler=pg_lo_open($c,$oid,"w"); 
						pg_lo_write($handler,$seq);
						pg_lo_close($handler); 
						

				
						pg_query($c,"commit");
						}
						else print "-";


						
					}
					else
					{
						// THE CURRENT GENE ALLREADY exists the system will update it !! 
						$cptupdategenes++;
						$mol_id=$row0["GENE_ID"];
						$requete="UPDATE \"GENE\" set \"NAME\"='$name' where \"GENE_ID\"='$mol_id' ";
						fputs($fdwrite,$requete."\n");
						//echo "$requete<br>";
						if ($test=="n")
						{	
						
					pg_query($c,"begin");
						$stmt4=pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));

						$oid2=pg_lo_create($c);
									$requete="UPDATE \"SEQUENCE\" set \"LENGTH\"='$size', \"SEQUENCE\"='$oid2', \"COMMENTS\"='$seqcomments' where \"MOL_ID\"='$mol_id'";	
									//echo "$requete<br>";
									if ($test=="n")
									{
									$stmt5=pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
									$handler=pg_lo_open($c,$oid2,"w"); 
									pg_lo_write($handler,$seq); 
						
					pg_query($c,"commit");
								
									}
									else
										//echo"FAKE UPDATE OF GENE and SEQUENCE<br>";
									print "-";
						}
					//ocifreestatement($stmt0);
					}
					
					
									
				}
			
					
					
			$seq="";	
			
			}
	
			
		}
	$cpt=$cpt-1;
	echo "<br><strong>DONE : $cpt sequences found<br></strong> ";
	fputs($fdwrite,"************************DONE : $cpt sequences added******************\n");
	echo " <br><strong>$cptnewgenes new genes inserted<br> $cptupdategenes genes updated</strong><br>";
	
	} 

}




?>

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