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



<?php

$test=$_POST["test"];
if($test!='y'){
	$test='n';
}else print "test mode<br>";


$species=$_POST["species"];
if(strlen($species)<=0){
	print "Error: Please select a species.<br>";
	return;
}


$count=0;
//$requete="select \"GENE_ID\" from \"GENE\", \"MOL_ENTITY\" where \"GENE_ID\"=\"MOL_ID\" and \"SPECIES\"='$species'";
$requete="SELECT \"GENE_ID\" from \"GENE\" where \"NAME\" like 'ci01001%'";

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

while($rowG=pg_fetch_array($stmtG)){

    $cluster=$rowG["GENE_ID"];
    if($test=="y")
        print "<br><br><strong>Gene:$cluster</strong><br>";
		
		if($test=="n"){
		pg_query($c,"begin");
		//delete les anciens resultats
		$requete="DELETE from \"DDD\" where \"GENE_ID\" = $cluster";
	
		$stmt3 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
		pg_query($c,"commit");
		//print "Old results deleted<br>";
				}
		
		
		
	$requete="select * from \"LIBRARY\" where \"SPECIES\"='$species' order by \"ORDRE\" ASC";
	//$requete="select * from ciona_design.library order by ordre ASC";
    $stmt = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
	
	while($row=pg_fetch_array($stmt)){
		
		
		$requete2="select count(distinct B.\"CLONE_ID\") AS \"RES\" from \"CLONE_SEQ\" A, \"CLONE\" B where A.\"ANISEED_CLUSTER_ID\"='$cluster' and (A.\"CLONE_NAME\"=B.\"CLONE_NAME\") and B.\"LIBRARY_ID\"=".$row["LIBRARY_ID"];
		$stmt2 = pg_query($c,$requete2) or die("<strong>Error</strong> ".pg_last_error($c));
	    if($row2=pg_fetch_array($stmt2)){
	        $value=$row2["RES"];
		    if($value > 0){
			    if($test=="y")
			        print "$value--".round( 1000*($value/$row["LIB_SIZE"]), 4)."--".$row["COMMENTS"]."--".$row["TISSUE"]."<br>";
				else if($test=="n"){
				    //recording
					pg_query($c,"begin");
					$requete="insert into \"DDD\" (\"LIBRARY_ID\",\"GENE_ID\",\"EXP_LEVEL\",\"CLONE_COUNT\") values('".$row["LIBRARY_ID"]."',".$rowG["GENE_ID"].",".( 1000*($value/$row["LIB_SIZE"])).",$value)";
					$stmt3 = pg_query($c,$requete) or die("<strong>Error</strong> ".pg_last_error($c));
					
					pg_query($c,"commit");
					++$count;
				}
			}
		}
	}
}


print "<br><br>Done: $count records<br>";
?>


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