<?php
/*
    ANISEED, NISEED System and Database
    Copyright (C) 2007 Olivier Tassy, Fabrice Daian, Patrick Lemaire

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/
include("connection.php");
//Title before frames_header
print '<title>ANISEED - DDD results</title>';

include("frames_header.php");
?>

<center>

<?php
	

	$explev="";
	$level="";
	$species="";
	$sort="";
	$group1="";
	$group2="";
	$genelist="";
	
    if(isset($_POST["explev"]))
		$explev=$_POST["explev"];
	if(isset($_POST["level"]))
		$level=$_POST["level"];
	if(isset($_POST["species"]))
		$species=$_POST["species"];
	if(isset($_POST["sort"]))
		$sort=$_POST["sort"];
	if(isset($_POST["group1"]))
		$group1=$_POST["group1"];
	if(isset($_POST["group2"]))
		$group2=$_POST["group2"];
	if(isset($_POST["genelist"]))
		$genelist=$_POST["genelist"];


// CONVERTIR la liste de gene genelist 
	
if (strlen($genelist)>0)
	{
	//print "=>".$genelist."<br>";
	$tmp=explode(":",$genelist);
	$genelist="";
	for ($i=0;$i<count($tmp);$i++)
	{
	$requete="SELECT \"NAME\" from \"GENE\" where \"GENE_ID\" in (SELECT \"GENE_MODEL_ID\" from \"GENE_CONCEPT\" where \"GENE_CLUSTER_ID\"='".str_replace("aniseedV3_","cluster",$tmp[$i])."')";
	$stmt=pg_query($c,$requete);
// 	print $requete."<br>";
	
	while ($row=pg_fetch_array($stmt)) if (strlen($genelist)==0) $genelist=$row["NAME"]; else $genelist.=":".$row["NAME"];
	}
	$genelist.=":";
	}

// print $genelist;
// return;








	$list1=(array) null;
	$list2=(array) null;
	
	if(is_array($group1))
    	$list1=(join("','",$group1));
	if(is_array($group2))	
		$list2=(join("','",$group2));


    if((count($group1)<=0)or(count($group2)<=0)){
	    print "<center><strong>Please select at least two groups of libraries<strong></center>";
		include("frames_footer.php");
		return;
	}
	
/////////////////////////////////////////////////////////////////////////////////////////////////////////
	
    $requete="select sum(\"LIB_SIZE\") as compte from \"LIBRARY\" where \"LIBRARY_ID\" in ('$list1')";	
    $stmt = pg_query($c,$requete);
	if($row=pg_fetch_array($stmt)){
		$N=0+$row["compte"];
		//print "=>>>".$row["compte"];
	}else $N=0;
	
    $requete="select sum(\"LIB_SIZE\") as compte from \"LIBRARY\" where \"LIBRARY_ID\" in ('$list2')";	
    $stmt = pg_query($c,$requete);
	if($row=pg_fetch_array($stmt)){
		$M=0+$row["compte"];
	}else $M=0;
	
	
	
	if(strlen($genelist)>0)
		print "<center><H2><font color=\"#FF6600\">Refining subset mode</font></H2></center>";
	
	
print "<center><font color=\"#D64242\" size=\"3\"><strong>DDD result<strong></font></center><br><br>";
	
	print '<table width="99%" border="0" cellspacing="0" cellpadding="0">';
	print '<tr align="center" valign="middle"><td><font color="#456898" size="2"><b>Differential /00</b></font></td><td><strong>&nbsp;</strong></td><td><font color="#456898" size="2"><b>P %</b></font></td><td><font color="#456898" size="2"><b>Gene model</b></font></td><td width="60%"><font color="#456898" size="2"><b>Biological name</b></font></td></tr>

	<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';

print '<tr valign="top"><td><hr size="1"></td><td><hr size="1"></td><td><hr size="1"></td><td><hr size="1"></td><td><hr size="1"></td></tr>';

	$count=0;
    //$requete="select A.\"GENE_ID\", A.\"NAME\" from \"GENE\" A, \"MOL_ENTITY\" B where (B.\"SPECIES\"='$species') and (A.\"GENE_ID\"=B.\"MOL_ID\")";	
    
	//$requete="SELECT A.\"GENE_ID\" from \"GENE\" A where A.\"NAME\" like 'c%'";
	$requete="SELECT A.\"GENE_ID\", A.\"NAME\" from \"GENE\" A";



	if( strlen($genelist)>0){
		$genelist = substr($genelist, 0, strlen($genelist)-1);
		$genelist = ereg_replace(":","','",$genelist);

		$requete.=" where (A.\"NAME\" in('".$genelist."'))";
	}
//  	print $requete;
	$stmt2 = pg_query($c,$requete);
	
	$genelist="";
	while($row2=pg_fetch_array($stmt2)){
//echo "compte  ".microtime()."<br>";
		$a="";
		$b="";
		$requete="select sum(\"CLONE_COUNT\") as compte from \"DDD\" where \"LIBRARY_ID\" in ('$list1') and \"GENE_ID\"='".$row2["GENE_ID"]."'";	
		$stmt = pg_query($c,$requete);
		if($row=pg_fetch_array($stmt)){
			$a=0+$row["compte"];
			
		}else $a=0;
		
		$requete="select sum(\"CLONE_COUNT\") as compte from \"DDD\" where \"LIBRARY_ID\" in ('$list2') and \"GENE_ID\"='".$row2["GENE_ID"]."'";	
		$stmt = pg_query($c,$requete);
		if($row=pg_fetch_array($stmt)){
			$b=0+$row["compte"];
		}else $b=0;
//echo "math  ".microtime()."<br>";

		if($N>0)
		    $ab=round(1000*($a/$N),4);
		else
		    $ab=0;
			
		if($M>0)
		    $ba=round(1000*($b/$M),4);
		else
		    $ba=0;
		
		if($explev==1){
			if( $ab>$ba ){
				if(($ab>0)and($ba>0))
					if(($ab/$ba)<$level)
						continue;
			}else{
				if(($ab>0)and($ba>0))
					if(($ba/$ab)<$level)
						continue;
			}
		}
			
		if( ($a==0)and($b==0) )
		    continue;
		if( ($sort==2)and( ($a/$N)<($b/$M) ) )
		    continue;
		if( ($sort==3)and( ($a/$N)>($b/$M) ) )
		    continue;
		
//echo "clav".microtime()."<br>";
		//see claverie genome research 97
		if ( eregi("^win", php_uname('s')) )  //if running under windows
			$res=trim(`winflat -xvalue $a -yvalue $b -diff $N $M`);
		else                                  //else try a unix command
			$res=trim(`./winflat -xvalue $a -yvalue $b -diff $N $M`);
			
//echo "formatage".microtime()."<br>";
		
		$p3=ereg("\) = ([^ \n]+)",$res,$arg);
		$p3=(float) $arg[1];
		$p2=ereg("\) = ([^ \n]+)$",$res,$arg);
		$p2=(float) $arg[1];



		$p=abs($p3-$p2);
		if($p>=0.95){
		//if($p<=0.05){
			++$count;
		    //recherche des noms du gene
			$requete="SELECT \"SYNO\", \"ORIGIN\" FROM \"SYNO\" WHERE \"GENE_ID\"=".$row2["GENE_ID"]." order by \"ORIGIN\" DESC";
			$stmt = pg_query($c,$requete);
			$names=""; $a=0;

		    while($row=pg_fetch_array($stmt)){
			    
			    if($row["SYNO"]==$row2["NAME"])
				    continue;
				
				if(++$a>1)
				    $names.=' <strong><font color="000000">/</font></strong> ';
			    $names.=$row["SYNO"];
				if($row["ORIGIN"]=="user-JGI")
				    $names.="*";
					
                //la chaine affichee ne doit pas depasser 100 char.
                //on ne prend en compte que l'affichage et pas le code html dans la mesure
				if( strlen($names)-(($a-1)*48) > 100 ){
				    $names.=" <strong><font color=\"000000\">/</font></strong>...";
					break;
				}
				
			}
			if($a==0){
				$requete="select \"DESCRITPION\", \"EVALUE\" from \"BLAST\" where \"MOL_ID\"='".$row2["GENE_ID"]."' and \"SCORE\"=(select max(\"SCORE\") from \"BLAST\" where \"MOL_ID\"='".$row2["GENE_ID"]."')";
				//$requete2="select max(score), description, evalue from ciona_design.blast where mol_id=$id";
				$stmt = pg_query($c,$requete);
				if($row=pg_fetch_array($stmt)){
					$eval = $row["EVALUE"];
					if( $eval <= 1e-10)
						$names.= "HIGHLY ";
					else if( ($eval >= 1e-4) and ($eval <= 1e-3) )
						$names.= "WEAKLY ";
					if($eval <= 1e-3)
						$names.= "SIMILAR TO ".$row["DESCRIPTION"]." (Eval: $eval)";
				}
				
			}

			
			
			print '<tr><td>';
			


			if( $ab>$ba ){
				print "<font size=\"-1\" color=\"#656565\">A($ab) &gt; B($ba)</font>&nbsp;</td><td>";
				if(($ab>0)and($ba>0))
					print "<font size=\"-1\" color=\"#656565\"><b>".round($ab/$ba,1)."x</b></font>";
			}else{
				print "<font size=\"-1\" color=\"#000000\">A($ab) &lt; B($ba)</font>&nbsp;</td><td>";
				if(($ab>0)and($ba>0))
					print "<font size=\"-1\" color=\"#656565\"><b>".round($ba/$ab,1)."x</b></font>";
			}

		    $p=round(100*$p,1);
		    //$p2=round(100*$p2,1);
			
			print '&nbsp;</td><td><font size="-1"><b>'.$p/*."(-$p3-$p2-)".'<br> a:'.$a.' b:'.$b.' M:'.$M.' N:'.$N*/.'&nbsp;</b></font></td><td align="center"><a href="molecule-gene.php?name='.$row2["NAME"].'"><font size="-1" color="#000000">'.$row2["NAME"].'</font></a>&nbsp;</td><td align="center"><font size="-1" color="#656565">'.$names.'</font></td></tr>';
			print '<tr valign="top"><td><hr size="1"></td><td><hr size="1"></td><td><hr size="1"></td><td><hr size="1"></td><td><hr size="1"></td></tr>';
		
		    $genelist.=$row2["NAME"].':';
		}
//echo "fin".microtime()."<br>";
	}
    print '</table>';
	
	if($count==0){
		print "<br><br><center><h2><strong>No match</strong></h2></center><br><br>";
	}else{
		print "<br><br>$count results";
		print "</center><br><br>* Manual annotation<center>";
	}

print '<form name="formulaire2" action="AllGenesFASTA.php" method="post">';
print '<input type="hidden" value="'.$genelist.'" name="id">';
print '&nbsp;&nbsp;&nbsp;<input name="submit" type="image" src="pictures/button-sequence.jpg" onClick="submit">';
print '</form>';

if(substr_count($genelist,":")<1000){
	print '<form name="formulaire3" action="" method="post">';
	print '<input type="hidden" value="'.$genelist.'" name="genelist">';
	print'&nbsp;&nbsp;&nbsp;
	
	<input name="submit" type="image" src="pictures/button-subset.jpg" onClick="javascript: window.document.formulaire3.action= window.document.formulaire3.redirect.value; submit;">';
	
	print '<br>
		   <select name="redirect" size="1">
			   <option value="GO-search.php">Gene ontology</option>
			   <option value="IP-search.php">Interpro</option>
			   <option value="insitu-search.php">In situ</option>
			   <option value="DDD-search.php">Digital Differential Display</option>
			   <option value="MW-search.php">Molecular weight</option>
			   <option value="ID.php">Export ID list</option>
		   </select>';
		   
	print '</form>';
}else{print '<font size="-1" color="#999999">Refine mode not available for set > 1000</font>';}
?>

</center>

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