<?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/>.

*/
header('Content-Type: text/plain');
include("connection.php");
?>
<?php
	//connection
	
	
		$species="";
		$words="";
		$genelist="";
	
		if(isset($_POST["species"]))
			$species=$_POST["species"];
		if(isset($_POST["ip"]))
			$words=explode("@",$_POST["ip"]);
			
			

		if(isset($_POST["genelist"]))
			$genelist=$_POST["genelist"];
			

		if (isset($_POST["notin"]))
			$notin=$_POST["notin"];


//////		//molecular weight parameters
/*
		if($_GET["mwc"]==0)
			$mwc=">";
		else
			$mwc="<";
		$mw=$_GET["mw"];
*/
		
		
      

		/*$query="'$words[0]'";*/
		
print "INTERPRO";
for($a=1; $a<count($words); ++$a) print "\t".$words[$a];
print "\n";
		
		
		//recherche des termes enfants a inclure dans la requete suivante
		/*$requete="SELECT DISTINCT IP_ID FROM CIONA_DESIGN.IP_CHILD_OF CONNECT BY CHILD_OF = PRIOR IP_ID START WITH IP_ID in (".$query.")";
		$stmt = OCIParse($connection, $requete);
		OCIExecute($stmt);
		while( OCIFetch($stmt) ){
			$query.=", '".OCIResult($stmt,"IP_ID")."'";
		}*/









/* SIMULATION D'UNE REQUETE SUR HIERARCHIE PAR UNE PROCEDURE DE REQUETES RECURSIVES */


function select_recursif_descendant($conn,$start,$res)
{
$res.=$start.",";
/*ON ECRIT SA REQUETE*/
$requete="SELECT distinct * FROM \"IP_CHILD_OF\" WHERE \"CHILD_OF\"=".$start." ";


$stmt=pg_query($conn,$requete);
while ($row=pg_fetch_array($stmt))
	{
	$res=select_recursif_descendant($conn,"'".$row["IP_ID"]."'",$res);
	}
return $res;
}

$result="";
for ($a=0;$a<count($words);$a++)
{
$words[$a]="'".$words[$a]."'";
$result=select_recursif_descendant($c,$words[$a],$result);
$query.=$result;
}
$query=substr($query,0,strlen($query)-1);

/* FIN DE LA SIMULATION */











		
		
		if ($notin!='y')
{
		
		$requete="SELECT distinct B.\"NAME\", B.\"GENE_ID\", C.\"SPECIES\" FROM \"IP_DESCRIPTION\" A, \"GENE\" B, \"MOL_ENTITY\" C WHERE (A.\"MOL_ID\"=B.\"GENE_ID\") and (A.\"MOL_ID\"=C.\"MOL_ID\") and (A.\"IP_ID\" in (".$query.") )";
		
		if( strlen($species)>1 )
		    $requete.=" AND (C.\"SPECIES\" ='$species')";
		//////if( $mw>0 )
		//////	$requete.=" AND (B.MW".$mwc.$mw.")";
		
		if( strlen($genelist)>0){
		    $genelist = substr($genelist, 0, strlen($genelist)-1);
		    $genelist = ereg_replace(":","','",$genelist);

			$requete.=" AND (B.\"NAME\" in('".$genelist."'))";
		}

}
else
{
$requete="SELECT distinct B.\"NAME\", B.\"GENE_ID\", C.\"SPECIES\" FROM \"IP_DESCRIPTION\" A, \"GENE\" B, \"MOL_ENTITY\" C WHERE (A.\"MOL_ID\"=B.\"GENE_ID\") and (A.\"MOL_ID\"=C.\"MOL_ID\") and (A.\"IP_ID\" not in (".$query.") )";
		
		if( strlen($species)>1 )
		    $requete.=" AND (C.\"SPECIES\" ='$species')";
		//////if( $mw>0 )
		//////	$requete.=" AND (B.MW".$mwc.$mw.")";
		
		if( strlen($genelist)>0){
		    $genelist = substr($genelist, 0, strlen($genelist)-1);
		    $genelist = ereg_replace(":","','",$genelist);

			$requete.=" AND (B.\"NAME\" in('".$genelist."'))";
		}
$requete.="EXCEPT SELECT distinct B.\"NAME\", B.\"GENE_ID\", C.\"SPECIES\" FROM \"IP_DESCRIPTION\" A, \"GENE\" B, \"MOL_ENTITY\" C WHERE (A.\"MOL_ID\"=B.\"GENE_ID\") and (A.\"MOL_ID\"=C.\"MOL_ID\") and (A.\"IP_ID\" in (".$query.") )";
		
		if( strlen($species)>1 )
		    $requete.=" AND (C.\"SPECIES\" ='$species')";
		//////if( $mw>0 )
		//////	$requete.=" AND (B.MW".$mwc.$mw.")";
		
		if( strlen($genelist)>0){
		  	$requete.=" AND (B.\"NAME\" in('".$genelist."'))";
		}
}




		
		
		$stmt = pg_query($c,$requete);
		
	
	
        
		$count=0;
		$genelist="";
		while( $row=pg_fetch_array($stmt) ){
		    //recherche des noms du gene
			$requete="SELECT \"SYNO\", \"ORIGIN\" FROM \"SYNO\" WHERE \"GENE_ID\"=".$row["GENE_ID"]." order by \"ORIGIN\" DESC";
			$stmt2 = pg_query($c,$requete);
			$names=""; $a=0;
		    while( $row2=pg_fetch_array($stmt2) ){
			    
			    if($row2["SYNO"]==$row["NAME"])
				    continue;
				
				if(++$a>1)
				    $names.='/';
			    $names.=$row2["SYNO"];
				if($row2["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.="/...";
					break;
				}
				
			}
			if($a==0){
				$requete="select \"DESCRIPTION\", \"EVALUE\" from \"BLAST\" where \"MOL_ID\"='".$row["GENE_ID"]."' and \"SCORE\"=(select max(\"SCORE\") from \"BLAST\" where \"MOL_ID\"='".$row["GENE_ID"]."')";
				$stmt2 = pg_query($c,$requete);
				if($row2=pg_fetch_array($stmt2)){
					
					$eval = $row2["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 ".$row2["DESCRIPTION"]." (Eval: $eval)";
				}
			}
			
			
			
			//$names=ereg_replace(".+ <strong><font color=\"000000\">/</font></strong> ","",$names);
			
		    ++$count;
			//////print "<tr align=\"center\" valign=\"top\" >"."<td><a href=\"molecule-gene.php?name=".OCIResult($stmt,"NAME")."\">".OCIResult($stmt,"NAME")."</a></td><td>$names</td><td>".OCIResult($stmt,"MW")."</td><td>".OCIResult($stmt,"SPECIES")."</td></tr>";
	if ($names=="") print "GENE_ID\t".$row["NAME"]."\tSPECIES\t".$row["SPECIES"]."\n";
	else	print "GENE_ID\t".$row["NAME"]."\tPOSSIBLE_NAME\t$names\tSPECIES\t".$row["SPECIES"]."\n";

			
		    $genelist.=$row["NAME"].":";  //liste les gene id pour rechercher les in situs.
		}
		
		
		if($count==0)
		    print "NO_MATCH_FOUND\n//\n";
		

        //print'<br><br><strong>GeneID list:</strong><br><textarea cols="80" rows="8">'.$genelist.'</textarea><br>You can copy/paste the GeneID list into the "in situ search" page to mine expression patterns of this protein family';
		/*
		print '<form name="formulaire" action="expression-analysis.php" method="post">';
		print '<input type="hidden" value="'.$genelist.'" name="genelist">';
		print '<input type="hidden" value="1" name="type">';
		print'<br><br><img src="pictures/button-expression.jpg" onClick="javascript: submit();">';
		print '</form>';
        */

?>