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


<?php

// get the previous option of the add_library.php

$cptnewcloneseq=0;
$cptupdatecloneseq=0;

if (isset($_GET["test"]))
	$test=$_GET["test"];
else 
$test="n";


if (isset($_GET["update"]))
	$update=$_GET["update"];
else 
$update="n";



if (isset($_GET["lib_id"]))
	$lib_id=$_GET["lib_id"];
else 
$lib_id="";
if ($lib_id=="null")
$lib_id="";

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

if (isset($_GET["species"]))
{
	$species=$_GET["species"];
}
else
{
	echo "<H3>ERROR: please select a species</H3>";
	include ("frames_footer.php");
	return;
}

if (isset($_GET["first5"]))
	$first5=$_GET["first5"];
else 
$first5="";

if (isset($_GET["last5"]))
	$last5=$_GET["last5"];
else 
$last5="";

if (isset($_GET["first3"]))
	$first3=$_GET["first3"];
else 
$first3="";

if (isset($_GET["last3"]))
	$last3=$_GET["last3"];
else 
$last3="";


// this file will contain all the clone where a name can't be found !!
// Usefull for the no name clones in cin.seq.all
/*
$pathtowrite2="./Unigene/clones_without_name.txt";
if(!($fdwrite2=fopen ($pathtowrite2, "w")))
{
	//echo" ERROR : Can't create the file :$pathtowrite <BR>";
	include("frames_footer.php");
	return;
}
else
{
	echo" The file $pathtowrite2 is created<BR>";
}
*/

/*
// log file
$pathtowrite="./Unigene/addclonelog.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);
*/

 //echo "<br>test ==== $test ////  species ====$species //// path ==== $path   ////lib_id====$lib_id <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 $path is open <BR>";
		$buffer = fgets($fdread, 4096);
		$cpt=1;
		$seq="";
		
		// getting the information of the description line of the sequence...
		while(!feof($fdread))
		{
			
			if ( ereg("^>(.+)", $buffer, $tabinfo))
			{
				
				$ligne="----$cpt----";
				
				//echo "$ligne <br>";
				fputs($fdwrite,"----$cpt----\n");
				
				$info=$tabinfo[1];
				$cpt++;
					
				// getting the informations !!! /clone=xxxxx /gb=xxxxxx 
				// getting the clone name 
				$info=str_replace("'", "",$info );
				$desc=trim($info);
				//echo "DESCRIPTION= $desc <br>";
				if ( (ereg("/clone=([^ /]+)",$info,$tabclonename)) || (ereg("clone:([^ /,]+)",$info,$tabclonename)) )
				{
					
					$clonename=rtrim($tabclonename[1]);
					$type="EST";
					$ligne= "Clone = $clonename // ";
					echo "$ligne ";
					fputs($fdwrite,$ligne);
					
				}
				else
				{
					fputs($fdwrite2,$desc."\n");
					$clonename="";
					$original_clone="";
					//echo " <br> PB : No clone name for this sequence !!!!!<br> ";
					fputs($fdwrite,"PB : No clone name found for this sequence  \n");
					
			
				}
				
				if ($clonename=="")
				{
					
					//echo " <br> PB : No clone name for this sequence !!!!!<br> ";
					$tname=split("\ ",$info);
					$name=trim($tname[1]);
					echo "$name <br><br>";
					if (ereg("^ci.+", $name) && $name!="Ciona")
					{
						$clonename=$name;
//						echo "<H2>NAME DEDUCTED FROM THE DESCRIPTION  = $clonename </H2><br>";
					}
					else 
					{
						$clonename="";
						$original_clone="";
						$type="cDNA";
					}
				}
				
				if(ereg("/clone_end=([^ /]+)",$info,$tabend))
				{
					$tmpend=str_replace("'", "",$tabend[1]);
					$end=$tmpend;
					//echo "Clone End = $end<br>";
					$type="EST";
				}
				else
				{
					$end="";
					//echo " <br> PB : No Clone_end for this sequence !!!!!<br> ";
				}
				
				
				
			// getting the gb id 
				if(ereg("/gb=([^ /]+)",$info,$tabgb))
				{
					$gb=$tabgb[1];
					echo "gb = $gb<br>";
					fputs($fdwrite," gb = $gb \n");
				}
				else
				{
					//echo " <br> PB : No gb for this sequence !!!!!<br> ";
					fputs($fdwrite,"PB : No gb found for this sequence. \n");
				}
				$buffer = fgets($fdread, 4096);
				
			}
			if (ereg("^#",$buffer))
				$buffer = fgets($fdread, 4096);
			
			if (!ereg("^#", $buffer) && !ereg("^>",$buffer))
			{
				
				while ( !ereg("^>(.+)", $buffer, $tabinfo) && (!ereg("^#",$buffer)) && (!feof($fdread)) )
				{
				
					$seq=$seq.$buffer;
					$buffer = fgets($fdread, 4096);
				}
				//echo "<br> SEQUENCE= $seq <br>";
				
				$seq=strtoupper($seq);
				$freqA=substr_count(strtoupper ($seq), "A"); 
				//echo "<br>freq A = $freqA";
				$freqG=substr_count(strtoupper ($seq), "G"); 
				//echo "<br>freq G  = $freqG";
				$freqC=substr_count(strtoupper ($seq), "C"); 
				//echo "<br>freq C = $freqC";
				$freqT=substr_count(strtoupper ($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><br><P>STATS SEQ===$seqcomments<br>";
				fputs($fdwrite,"STATS SEQ===$seqcomments // size= $size \n");
				
				$data = $seq;
				/*
				$result = count_chars($data, 0);

				for ($i=0; $i < count($result); $i++) {
   				if (($result[$i] != 0) && (chr($i)!="\n" && chr($i)!=" "))
      			echo "Il y avait $result[$i] occurrence(s) de \"" , chr($i) , "\" dans la phrase.<br>";
				}
				*/
				
				// construction du bon nom du clone en prenant en compte les informations entr�s par les options !!!
				if ($first5!="" or $last5!="" or $first3!="" or $last3!="")
				{
					if (ereg("^".$first3."(.+)".$last3."$",$clonename,$clone) && $end!="5" && $clonename!="")
					{
//						echo "<br>3' CASE :";
						//echo "*******clonename= $clonename";
						$end="3";
						$type="EST";
						$original_clone=$clone[1];
//						echo "----->Principal name = $original_clone <br>";
						fputs($fdwrite," 3' CASE----->Principal name = $original_clone \n");
						
						
						
					}
					else if (ereg("^".$first5."(.+)".$last5."$",$clonename,$clone) && $end!="3" && $clonename!="")
					{
//						echo "<br>5' CASE :";
						//echo "*******clonename= $clonename";
						$end="5";
						$type="EST";
						$original_clone=$clone[1];
//						echo "----->Principal name = $original_clone <br>";
						fputs($fdwrite,"5' CASE----->Principal name = $original_clone \n");
					}
					else
					{
//						echo "<br> Undetermined CASE";
//						echo "*******clonename= $clonename";
						$original_clone=$clonename;
						$end="";
						//$type="cDNA";
//						echo "----->Principal name = $original_clone <br>";
						fputs($fdwrite,"CAS Undetermined----->Principal name = $original_clone \n");
					}
				}
				else 
				{
					if(($end!="3")&&($end!="5")&& $clonename!="")
						$type="cDNA";
					//echo "3' et 5' no dif !!!<br>";
					$original_clone=$clonename;
					//echo "no dif------>CLONE NAME= $original_clone<br>";
					fputs($fdwrite,"CAS no dif----->Principal name = $original_clone \n");
					
				}
				
				if (($original_clone!="") && ($clonename!="") )
				{
					// Only if the library is not the global library as CINSEQALL
			
					if ($lib_id!="")
					{
							
						$requete="select \"CLONE_ID\" from \"CLONE\" where \"CLONE_NAME\"='$original_clone'";
						$stmt0 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
						echo "REQUETE=$requete";
						$row0=pg_fetch_array($stmt0);
						if (pg_num_rows($stmt0)==0)
						//if(!$row0=pg_fetch_array($stmt0))
						{
						//print "ici";
							$requete="INSERT INTO \"BIO_ENTITY\" (\"BIO_ID\", \"CURATED\" ) values ( nextval('\"S_BIO_ID\"'),'y')";

							//echo "requete=$requete<br>";
							if ($test=="n")
							{
			/* Lancement de la transaction */pg_query($c,"begin");
								$stmt1= pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
								/*if(!OCIExecute($stmt1,OCI_DEFAULT) )
								{
									OCIRollback($connection);
									print "ERROR";
									return;
								}
								ocifreestatement($stmt1);*/
							}
//							else echo "<br>CLONE not find into ANISEED : (fake1 ---->table bio_entity) $requete<br>";
				/*y'avait currval avant*/$requete="INSERT INTO \"MOL_ENTITY\" (\"MOL_ID\", \"SPECIES\", \"NAME\", \"TYPE\" ) values (currval('\"S_BIO_ID\"'),'$species', '$original_clone', 'clone')";
							//echo "requete=$requete<br>";
							if ($test=="n")
							{
								$stmt1= pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
								/*if(!OCIExecute($stmt1,OCI_DEFAULT) )
								{
									OCIRollback($connection);
									print "ERROR";
									return;
								}
								ocifreestatement($stmt1);*/
							}
//							else 
//								echo "<br>CLONE not find into ANISEED : (fake2 ---->table mol_entity) $requete<br>";
			/*idem currval avant*/		$requete="INSERT INTO \"CLONE\" (\"CLONE_ID\", \"CLONE_NAME\", \"LIBRARY_ID\") values (currval('\"S_BIO_ID\"'), '$original_clone', '$lib_id')";
							//echo "requete=$requete<br>";
							if ($test=="n")
							{
								$stmt1= pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
								/*if(!OCIExecute($stmt1,OCI_DEFAULT) )
								{
									OCIRollback($connection);
									print "ERROR";
									return;
								}
								ocifreestatement($stmt1);*/
			/*Commit de la transaction*/pg_query($c,"commit");		
							// COMMIT DE LA CREATION DU CLONE
							/*	if (!OCICommit($connection) )
								{
									$error = OCIError($connection);
									echo "Commit failed: " . $error['message'];
									include("frames_footer.php");
									return;
								}*/
							
							}
							/*
							else 
							{
								echo "<br>CLONE not find into ANISEED : (fake3 ---->table clone) $requete<br>";
								
							}*/
						
						}
						//ocifreestatement($stmt0);
						
					}
					
					if ($lib_id!="")
					{
						//echo "<strong>UPDATE OF THE CLONE :::</strong><br>";
						$requete="Update \"CLONE\" set \"LIBRARY_ID\"='$lib_id' where \"CLONE_NAME\"='$original_clone' ";
						//echo "--------requete=$requete<br>";
						if ($test=="n")
						{
						pg_query($c,"begin");

							$stmt = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
						pg_query($c,"commit");							

						print "<br><center><H1>Update done</H1></center>";
						
						}
						//else
					
//							echo "(FAKE Update)----> $requete<br> ";
						//update du clone deja existant!!!!!!!
						// mise a jour de la librarie essentiellement
					}
				}
/*					
				else 
				{
					if ($lib_id!="")
						echo "<strong>ERROR: Clone name not find for this file !!</strong><br>";
					
				}
*/			
				
				if ($gb!="")
				{
					/*if ($lib_id=="")
					{
						$clonename="";
						$original_clone="";
					}*/
					
					$requete= "select \"CLONE_SEQ_ID\" from \"CLONE_SEQ\" where \"GENBANK_ID\"='$gb'";
					$stmt2 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
					if(!$row2=pg_fetch_array($stmt2))
					{
						
//						echo "<br><strong>GB NOT FOUND !! CREATION OF A NEW CLONE_SEQ</strong><br>";
						$cptnewcloneseq++;
						$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));
							/*if(!OCIExecute($stmt1,OCI_DEFAULT) )
							{
								OCIRollback($connection);
								print "ERROR";
								return;
							}
							ocifreestatement($stmt1);*/
						}
//					else 
//							echo"GB not found : (fake1 ---->table bio_entity) $requete<br>";
						if ($clonename!="")
							$requete="INSERT INTO \"MOL_ENTITY\" (\"MOL_ID\", \"SPECIES\", \"NAME\", \"TYPE\" ) values (currval('\"S_BIO_ID\"'),'$species', '$clonename', 'clone_sequence')";
						else
							$requete="INSERT INTO \"MOL_ENTITY\" (\"MOL_ID\", \"SPECIES\", \"NAME\", \"TYPE\" ) values (currval('\"S_BIO_ID\"'),'$species', '$gb', 'clone_sequence')";
						//echo "requete=$requete<br>";
						if ($test=="n")
						{
					
							$stmt1= pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
							/*if(!OCIExecute($stmt1,OCI_DEFAULT) )
							{
								OCIRollback($connection);
								print "ERROR";
								return;
							}
							ocifreestatement($stmt1);*/
						}
//						else 
//							echo"GB not found : (fake2 ---->table mol_entity) $requete<br>";
							
						if ($lib_id!="")
							$requete="INSERT INTO \"CLONE_SEQ\" (\"CLONE_SEQ_ID\", \"GENBANK_ID\", \"TYPE\", \"FULL_LENGTH\", \"END\", \"NAME\", \"CLONE_NAME\",\"COMMENTS\" ) values (currval('\"S_BIO_ID\"'),'$gb', '$type', '$size', '$end', '$clonename', '$original_clone', '$desc' )";
						else
							$requete="INSERT INTO \"CLONE_SEQ\" (\"CLONE_SEQ_ID\", \"GENBANK_ID\", \"TYPE\", \"FULL_LENGTH\", \"END\", \"NAME\", \"COMMENTS\" ) values (currval('\"S_BIO_ID\"'),'$gb', '$type', '$size', '$end', '$clonename', '$desc' )";
						fputs($fdwrite,$requete."\n");
						//echo "requete=$requete<br>";
						if ($test=="n")
						{
							$stmt1=pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
							/*if(!OCIExecute($stmt1,OCI_DEFAULT) )
							{
								OCIRollback($connection);
								print "ERROR";
								return;
							}
							ocifreestatement($stmt1);*/
						}
//						else 
//							echo"GB not found : (fake3 ---->table clone_seq) $requete<br>";
						
						// ajout de la s�uence corel� a clone_seq
						if ($test=="n")
						{
						$oid=pg_lo_create($c); /*Creation de l'oid de la sequence*/
						$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"); /*Ouverture du flux*/
						pg_lo_write($handler,$seq); /*Ecriture de la sequence*/
						pg_lo_close($handler); /*Fermeture du flux*/
						}

				
						pg_query($c,"commit");
						
						
													
					}
					else 
					{
						if ($update=='y')
						{
							$mol_id=$row2["CLONE_SEQ_ID"];
							$cptupdatecloneseq++;
							//echo "!!!!!! DUPLICATE ENTRY : << UPDATE CLONE_SEQ and SEQ >> <br>";
							if ($lib_id!="")
								$requete="UPDATE \"CLONE_SEQ\" set \"TYPE\"='$type', \"END\"='$end', \"NAME\"='$clonename', \"COMMENTS\"='$desc', \"CLONE_NAME\"='$original_clone', \"FULL_LENGTH\"='$size' where \"CLONE_SEQ_ID\"='$mol_id' ";
							else
								$requete="UPDATE \"CLONE_SEQ\" set \"TYPE\"='$type', \"END\"='$end', \"NAME\"='$clonename', \"COMMENTS\"='$desc',\"FULL_LENGTH\"='$size' where \"CLONE_SEQ_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"); /*Ouverture du flux*/
									pg_lo_write($handler,$seq); /*Ecriture de la sequence*/
									pg_lo_close($handler); /*Fermeture du flux*/
						
						pg_query($c,"commit");

										
									}
								
							//	$clob->free();
							//	OCIFreeStatement($stmt5);
							//	OCIFreeStatement($stmt4);
							//	$committed = OCICommit($connection);
								// Verification de la validation : si une erreur est survenue, afficher le message d'erreur
								/*if(!$committed) 
								{
									$error = OCIError($connection);
									echo 'ERROR: '.$error['message'];
								}*/
							}/*
							else 
								echo"FAKE UPDATE OF CLONE_SEQ and SEQUENCE<br>";
							*/
						}	
					}
					//ocifreestatement($stmt2);	
				}
				
								
				$seq="";
			}			
		}
		$cpt=$cpt-1;
		echo "<br><strong>OK : $cpt clone sequences added<br></strong> ";
		fputs($fdwrite,"************************DONE : $cpt clone sequences added\n \t Insert : $cptnewcloneseq \n\t Update : $cptupdatecloneseq ******************\n");
		echo " <br><strong>$cptnewcloneseq inserted and $cptupdatecloneseq updated</strong><br>";
		
		if ($lib_id!= "")
		{
			$cptclones=0;
			$requete="select \"CLONE_ID\" from \"CLONE\" where \"LIBRARY_ID\"='$lib_id' ";
			$stmt0 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
			
			while($row0=pg_fetch_array($stmt0))
			{
				$cptclones++;
			}
			if ($cptclones > 0)
			{
				
				$requete="UPDATE \"LIBRARY\" set \"LIB_SIZE\"='$cptclones' where \"LIBRARY_ID\"='$lib_id'";
				if ($test=="n")
				{
				pg_query($c,"begin");

					$stmt1 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
					
				pg_query($c,"commit");
				
				print "<br><center><H1>Library size updated</H1></center>";
					
				//	ocifreestatement($stmt1);
						
				}/*
				else
					echo "(FAKE Update)----> $requete<br> ";
					*/
			}
			//else 
			//	echo "ERROR : the size of the library is null<br> ";
		
		}
		
		fclose($fdread);
		fclose($fdwrite);
		fclose($fdwrite2);		
	}
}

?>

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