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

/*
reg-region-edit.php

AUTHOR: Daniel Sobral
12/12/2006

*/

function printhierarchy($c,$curr,$root,$level){
	for($i=0;$i<$level;$i++){
	  echo '&nbsp&nbsp&nbsp&nbsp|&nbsp';
	}	

	//print current promoter...
  	$khoueiry = "SELECT * FROM \"PROMOTER\" WHERE \"PROMOTER_ID\"=".$root.";";
	$stmt = pg_query($c,$khoueiry); 
	if($row=pg_fetch_array($stmt)){
	  
	    $img_html = "";
		if($root==$row["BASE_REG_ID"]){
		  	//$img_html .= '<img '.$img_ext.' src="pictures/reg_base.gif">';
		  	$img_html .= '&nbsp;&nbsp;';
	  	} elseif( ($row["DELETION"]=='y') || ($row["MUTATION"]=='y') || ($row["ADDITION"]=='y') ) {
	  	  	$img_html="";
			//if ($row["DELETION"]=='y'){ $img_html .= '<img '.$img_ext.' src="pictures/reg_deletion.gif">'; } 
			//if ($row["MUTATION"]=='y'){ $img_html .= '<img '.$img_ext.' src="pictures/reg_mutation.gif">'; } 
			//if ($row["ADDITION"]=='y'){ $img_html .= '<img '.$img_ext.' src="pictures/reg_addition.gif">'; }	
			if ($row["DELETION"]=='y'){ $img_html .= '&nbsp;&nbsp;(deletion)&nbsp;&nbsp;'; } 
			if ($row["MUTATION"]=='y'){ $img_html .= '&nbsp;&nbsp;(mutation)&nbsp;&nbsp;'; } 
			if ($row["ADDITION"]=='y'){ $img_html .= '&nbsp;&nbsp;(artificial modification)&nbsp;&nbsp;'; }	
		} else {
		  
		  	if($row["IS_NATURAL"]=='y'){
			  	$img_html .= '&nbsp;&nbsp;(natural variation)&nbsp;&nbsp;';			    
			} else {
			  	$img_html .= '&nbsp;&nbsp;(unknown change)&nbsp;&nbsp;';
			  	//$img_html .= '<img '.$img_ext.' src="pictures/reg_unknown.gif">';  
			}
		  	
		}						
		echo $img_html;
		
		if($curr==$root){		    		    
			echo '<font color="white"><strong>'.$row["NAME"].'</strong></font>'; 
		} else {
			echo $row["STABLE_ID"].':&nbsp;&nbsp;<a href="reg-region-edit.php?id='.$root.'">'.$row["NAME"].'</a>';  
		}		
		
		echo ' [ '.$row["TYPE"].' ]';
	} else {
		echo '<strong>Error getting information for region '.$root.'</strong>';
	}
	echo '<br/>';
	
	//print children... 
	$khoueiry = "SELECT * FROM \"PROMOTER\" WHERE \"BASE_REG_ID\"=".$root." AND \"BASE_REG_ID\"!=\"PROMOTER_ID\" ORDER BY \"BEGIN\" ASC, \"END\" DESC, \"NAME\";";
	$stmt = pg_query($c,$khoueiry); 
	while($row=pg_fetch_array($stmt)){
		printhierarchy($c,$curr,$row["PROMOTER_ID"],$level+1);    
	}	
}

function findroot($c,$base_id){  	
    $root = $base_id;  	
  	$khoueiry = "SELECT * FROM \"PROMOTER\" WHERE \"PROMOTER_ID\"=".$root.";";
	$stmt = pg_query($c,$khoueiry); 
	$row=pg_fetch_array($stmt); 	
	$protect = array();
	while($row!=false && $row["BASE_REG_ID"]!=$root){
		if(isset($protect[$row["BASE_REG_ID"]])){
			return null;
		}
		$root = $row["BASE_REG_ID"];
		$protect[$root] = 1;
	  	$khoueiry = "SELECT * FROM \"PROMOTER\" WHERE \"PROMOTER_ID\"=".$root.";";
		$stmt = pg_query($c,$khoueiry);
		$row=pg_fetch_array($stmt);
	}
	
	return $root;
}  


if ( (!isset($_SESSION["login"]))or(!isset($_SESSION["pass"])) ) {	
    print "<strong>you need to <a href=\"login.php\">login</a> to proceed.</strong>";
    include ("frames_footer.php"); 
	return;
}

/*
$test="SELECT * from \"AUTHOR\" where \"LOGIN\"='".$_SESSION["login"]."'";
$stest=pg_query($c,$test);
if (!$rtest=pg_fetch_array($stest)) {
	   print "<strong>you need to <a href=\"login.php\">login</a> to proceed.</strong>";
    include ("frames_footer.php"); 
	return;
}
*/

//print "<center><strong>Updates in progress.</strong></center>";
//include ("frames_footer.php");
//return;

$max_width = 600;		

$id=$_GET["id"];
    
//AUTHOR, ANNOTATOR AND CURATION INFO	
		    
$khoueiry="SELECT A.\"NAME\", A.\"SURNAME\", A.\"MAIL\", B.\"ENTRY_DATE\" FROM \"AUTHOR\" A, \"ENTRY_ORIGIN\" B WHERE  (B.\"BIO_ID\"=$id) AND (A.\"AUTHOR_ID\"=B.\"AUTHOR_ID\")";
	
$stmt = pg_query($c,$khoueiry);
if (! $rowcond=pg_fetch_array($stmt) ){
	print "Author: <strong>Warning - no author information!</strong>";
} else {
	echo 'Author: <strong><a href="mailto:'.$rowcond["MAIL"]."\">".$rowcond["SURNAME"]." ".$rowcond["NAME"]."</a></strong>&nbsp;&nbsp;&nbsp;".$rowcond["ENTRY_DATE"]."&nbsp;&nbsp;&nbsp;";  
}
	
echo '&nbsp;&nbsp;<a target="_BLANK" href="edit-author.php?id='.$id.'"><img border="0" width="25" title="Change the Author" src="pictures/button-cur-edit.gif"></a><br>';		
		
$rannot="SELECT \"ANNOTATOR_ID\",\"ANNOTATION_DATE\" from \"ENTRY_ORIGIN\" where \"BIO_ID\"='$id'";
$sannot=pg_query($c,$rannot);

//On fait afficher les informations sur l'annotator
$fetch=pg_fetch_array($sannot);
$annotator_id=$fetch["ANNOTATOR_ID"];
if (strlen($annotator_id)>0)
{
	$annotation_date=$fetch["ANNOTATION_DATE"];
	$rannot="SELECT \"NAME\",\"SURNAME\",\"MAIL\" from \"AUTHOR\" where \"AUTHOR_ID\"='$annotator_id'";
	$sannot=pg_query($c,$rannot);
	$fetch2=pg_fetch_array($sannot);
	print "Annotator: <strong> <a href=\"mailto:".$fetch2["MAIL"]."\">".$fetch2["SURNAME"]." ".$fetch2["NAME"]."</a></strong>&nbsp;&nbsp;&nbsp;$annotation_date&nbsp;&nbsp;&nbsp;";

	$test="SELECT \"IS_ADMIN\" from \"AUTHOR\" where \"LOGIN\"='".$_SESSION["login"]."'";
	$stest=pg_query($c,$test);
	$rtest=pg_fetch_array($stest);
	if ($rtest["IS_ADMIN"]=='y') {
		print '<a target="_blank" href="edit-annotator.php?id='.$id.'"><img border="0" width="25" src="pictures/button-cur-edit.gif"></a>';  
	}

	print "<br/>";
}


$rcura="SELECT \"CURATOR_ID\",\"CURATION_DATE\" from \"ENTRY_ORIGIN\" where \"BIO_ID\"='$id'";
$scura=pg_query($c,$rcura);

//On fait afficher les informations pour le curator
$fetch=pg_fetch_array($scura);
$curator_id=$fetch["CURATOR_ID"];
if (strlen($curator_id)>0)
{
	$curation_date=$fetch["CURATION_DATE"];
	$rcura="SELECT \"NAME\",\"SURNAME\",\"MAIL\" from \"AUTHOR\" where \"AUTHOR_ID\"='$curator_id'";
	$scura=pg_query($c,$rcura);
	$fetch2=pg_fetch_array($scura);
	print "Curator: <strong> <a href=\"mailto:".$fetch2["MAIL"]."\">".$fetch2["SURNAME"]." ".$fetch2["NAME"]."</a></strong>&nbsp;&nbsp;&nbsp;$curation_date&nbsp;&nbsp;&nbsp;";

	$test="SELECT \"IS_ADMIN\" from \"AUTHOR\" where \"LOGIN\"='".$_SESSION["login"]."'";
	$stest=pg_query($c,$test);
	$rtest=pg_fetch_array($stest);
	if ($rtest["IS_ADMIN"]=='y') {
		print '<a target="_blank" href="edit-curator.php?id='.$id.'"><img border="0" width="25" src="pictures/button-cur-edit.gif"></a>';  
	}

	print "<br/>";
}

//Affichage du statut de l'ISH
$private="";
$curated="";

print "<br><div align=\"center\">This entry is ";

$query="SELECT \"PRIVATE\",\"CHECKED\",\"BEING_CURATED\" from \"PROMOTER\" where \"PROMOTER_ID\"='$id'";
$statement=pg_query($c,$query);
$roww=pg_fetch_array($statement);

if ($roww["PRIVATE"]=='y') print "<font color=\"red\"><b>PRIVATE</b></font>";
else print "<font color=\"green\"><b>PUBLIC</b></font>";
print " and ";
if (($roww["CHECKED"]=='y')&&($roww["BEING_CURATED"]!='y'))print "<font color=\"green\"><b>CURATED</b></font>";
//if ($roww["CHECKED"]=='y') print "<font color=\"green\"><b>CURATED</b></font>";
else if (($roww["CHECKED"]=='y')&&($roww["BEING_CURATED"]=='y')) print "is <font color=\"orange\"><b>BEING MANUALLY CURATED</b></font>";
else print "<font color=\"red\"><b>NOT CURATED</b></font>";
print "</div><br>";
$private=$roww["PRIVATE"];
$curated=$roww["CHECKED"];
$being=$roww["BEING_CURATED"];
//Fin affichage tempo ISH

	echo '<form Method="POST" Action="reg-region-export-xml.php" name="formulaire" target="_blank">';
	
     //curation
	print '<div align="center" style="border:0px solid black;padding:3px;">';
	
	
$test="SELECT \"IS_ADMIN\" from \"AUTHOR\" where \"LOGIN\"='".$_SESSION["login"]."'";
$stest=pg_query($c,$test);
$rtest=pg_fetch_array($stest);

	if ($private=='y') print '
	&nbsp;<img src="pictures/button-make-public.jpg" border="1" style="border:2px solid green;" title="Make public: To make this entry publishable" onClick="window.open(\'curator-state.php?mode=1&id='.$id.'&type=reg\')">';
	else print '
	&nbsp;<img src="pictures/button-make-private.jpg" border="1" style="border:2px solid red;" title="Make private: To make this entry not publishable" onClick="window.open(\'curator-state.php?mode=2&id='.$id.'&type=reg\')">';
	
if ($rtest["IS_ADMIN"]=='y')
{
	if (($curated=='y') && ($being!='y'))
	print '
	&nbsp;<img src="pictures/button-make-not-curated.jpg" border="1" style="border:2px solid red;" title="Make not curated : To unpublish this entry" onClick="window.open(\'curator-state.php?mode=3&id='.$id.'&type=reg\')">';

	if (($curated=='y') && ($being=='y'))
	print '&nbsp;<img src="pictures/button-make-curated.jpg" border="1" style="border:2px solid green;" title="Make curated : To publish this entry, if it is publishable"  onClick="window.open(\'curator-validate.php?id='.$id.'&type=reg\')"><!--</div>-->';	
}
	if ((($private!='y') && ($curated=='y')) && ($being!='y')) print '
	&nbsp;<img src="pictures/button-make-being-curated.jpg" border="1" style="border:2px solid orange;" title="Make being curated: To make this entry being curated" onClick="window.open(\'make-being.php?id='.$id.'&type=reg\')">';

if ($rtest["IS_ADMIN"]=='y')
{

if ($curated=='n')
print '&nbsp;<img src="pictures/button-make-curated.jpg" border="1" style="border:2px solid green;" title="Make curated : To publish this entry, if it is publishable"  onClick="window.open(\'curator-validate.php?id='.$id.'&type=reg\')"><!--</div>-->';
print '<!--<div align="right">-->&nbsp;<img src="pictures/button-delete.jpg" style="border:2px solid black;" border="1" title="Delete this entry" onClick="window.open(\'reg-region-delete.php?id='.$id.'\')">';
}

	print '&nbsp;<img src="pictures/button-create-child.jpg" border="1" style="border:2px solid pink;" title="Create a child region"  onClick="window.open(\'reg-region-add-child.php?id='.$id.'\')"><!--</div>-->';
				

	echo "<input name=\"region_id_list\" type=\"hidden\" value=\"$id\">";
	echo '&nbsp;<input name="submit" type="image" src="pictures/button-export-xml.jpg" style="border:2px solid floralwhite;" onClick="submit">';
		
	print '</div>';

	echo '</form>';

print "<hr>";

//START OF THE REGION INFORMATION
	
    $khoueiry = "SELECT * FROM \"PROMOTER\" WHERE \"PROMOTER_ID\"=".$id.";";	
	$stmt = pg_query($c,$khoueiry);
	if($row=pg_fetch_array($stmt)){
	  
  	    $info[$id] = $row;
  	    
		$stable_id = $row["STABLE_ID"];
	    $name=$row["NAME"];
	    $comments=$row["COMMENTS"];
	    $begin = $row["BEGIN"];
	    $end = $row["END"];

   	    $deletion = $row["DELETION"];
   	    $mutation = $row["MUTATION"];
   	    $addition = $row["ADDITION"];
	    $base_id=$row["BASE_REG_ID"];	
	    
	    $is_natural = $row["IS_NATURAL"];
	    $type = $row["TYPE"];
	    
	    $length = 0;
	    $khoueiry="select \"LENGTH\" from \"SEQUENCE\" where \"MOL_ID\"=".$id.";";
		$stmt = pg_query($c,$khoueiry);		
		if($row=pg_fetch_array($stmt)){
			  $length = $row["LENGTH"];
		}
		
		print "<br/><a target=\"_BLANK\" href=\"curator-mol-edit.php?type=promoter&part=name&id=$id\"><img border=\"0\" width=\"25\" title=\"Change Name\" src=\"pictures/button-cur-edit.gif\"></a><strong><font size=\"+2\"><em>Regulatory Region ".$stable_id.": ".$name."</em></font></strong> <br/>";				
		
		print "<a target=\"_BLANK\" href=\"reg-region-origin-edit.php?id=$id\"><img border=\"0\" width=\"25\" title=\"Change Origin\" src=\"pictures/button-cur-edit.gif\"></a>";
		
		if($is_natural=='y'){
		  	$ann = "SELECT \"SPECIES\" FROM \"MOL_ENTITY\" WHERE \"MOL_ID\"=".$id;
	  	  	$sann=pg_query($c,$ann);
			$rann=pg_fetch_array($sann);	
			print "&nbsp;&nbsp;Natural Region from ".$rann["SPECIES"]."<br/>";  		  
		} else {
			print "&nbsp;&nbsp;Artificial Region</a>&nbsp;<br/>";  	
		}
		
		if($base_id != $id) {				
		
			
			//THE SO  -> for now there is only one... later this will no longer be like that...
			print "<a target=\"_BLANK\" href=\"reg-region-SO-edit.php?id=$id\"><img border=\"0\" width=\"25\" title=\"Change Annotation\" src=\"pictures/button-cur-edit.gif\"></a>";
			
		  	$ann = "SELECT \"DESCRIPTION\" FROM \"SO\", \"SO_DESCRIPTION\" WHERE \"SO\".\"SO_ID\"=\"SO_DESCRIPTION\".\"SO_ID\" AND \"PROMOTER_ID\"=".$id;
	  	  	$sann=pg_query($c,$ann);
			$rann=pg_fetch_array($sann);	
			if($rann){
				print "&nbsp;&nbsp;".$rann["DESCRIPTION"]."";  		  
			}	else {
				print "&nbsp;&nbsp;No annotation of effect of modification on intensity of expression";  		  
			}			
			
		}	
		print "&nbsp;<br/>";	

		

		//////////////////////////////////////////GBROWSE/////////////////////////////////////////////

	   	//if($is_natural=='y' && $deletion != 'y' && $mutation != 'y' && $addition != 'y'){
			//check if it has a previous blast
			$khoueiry="select * from \"PROMOTER_POS\" where \"PROMOTER_ID\"=$id ORDER BY \"BEGIN\"";
			$stmt = pg_query($c,$khoueiry);			
			if($row=pg_fetch_array($stmt)){		
				//I'm assuming the lines from 
				
				$confidence = $row["SURE"];
				$local_base = $row["LOCAL"];
				$begin_base = $row["BEGIN"];
				$end_base = $row["END"];
				$end_final = $end_base;
				
				$str_pos = "auto=".$local_base."+Match_result+".str_replace(" ","_",$name)."+".$begin_base."-".$end_base.";";				
				
				while($row=pg_fetch_array($stmt)){
					if($row["LOCAL"]!==$local_base){
						print "<br/><strong>Position of the genome likely to be incorrect!!</strong>";	
						break;
					}					
					
					$end_final = $row["END"];
					$str_pos = $str_pos."auto=".$local_base."+Match_result+".str_replace(" ","_",$name)."+".$row["BEGIN"]."-".$row["END"].";";					
				}
				
				$ref = "http://crfb.univ-mrs.fr/ciona-bin/gbrowse/intestinalis?name=".$local_base.":".($begin_base-500)."..".($end_final+500).";".$str_pos;
				//e.g multiple links 				//http://crfb.univ-mrs.fr/ciona-bin/gbrowse_img/intestinalis?name=scaffold_3:780572..781645;a=scaffold_3+TFBS+GATA(%2B)+781072..781076;a=scaffold_3+TFBS+ETS(%2B)+781085..781090;a=scaffold_3+TFBS+GATA(-)+781123..781127;a=scaffold_3+TFBS+ETS(-)+781145..781150;style=%22TFBS%22+glyph=box+fgcolor=red+bgcolor=red;
				
				//e.g. single link  http://crfb.univ-mrs.fr/ciona-bin/gbrowse/intestinalis?name=scaffold_98:245000..246000;auto=scaffold_98+Blast_results+Otx+245372-245459
				//$ref ="http://crfb.univ-mrs.fr/ciona-bin/gbrowse/intestinalis?name=".$row["LOCAL"].":".($row["BEGIN"]-500)."..".($row["END"]+500). ";auto=".$row["LOCAL"]."+Blast_result+".str_replace(" ","_",$name)."+".$row["BEGIN"]."-".$row["END"];						
				
				print "<br/>Position in the genome obtained: <a href=\"$ref\" target=\"_blank\">See it in Gbrowse</a>";	
				
			
				print "<br/><a href=\"reg-region-blast.php?id=$id\" target=\"_blank\">Recheck position in Genome</a>";
				
				
				
				if ($rtest["IS_ADMIN"]=='y')
				{				
					//Change the confidence status...
					if($confidence=='y'){						
						print "<br/>This position is trusted: <a href=\"reg-region-confirm-position.php?id=$id&sure=n\" target=\"_blank\"> Mark this position as NOT trusted to insert in GBrowse <img border=\"0\" width=\"25\" title=\"Mark position as NOT trusted \" src=\"pictures/button-cur-delete.gif\"> </a><br/>";
					} else {						
						print "<br/>This position is NOT trusted: <a href=\"reg-region-confirm-position.php?id=$id&sure=y\" target=\"_blank\"> Mark this position as trusted to insert in GBrowse <img border=\"0\" width=\"25\" title=\" Mark position as trusted \" src=\"pictures/button-cur-validate.gif\"> </a><br/>";
					}								
				}				
				
			} else {
				print "<a href=\"reg-region-blast.php?id=$id\" target=\"_blank\"> <img border=\"0\" width=\"25\" title=\"Find position in the genome \" src=\"pictures/zoom.gif\">Try to locate the region in the Genome</a><br/>";
			}	
			echo '<br/><br/>';
		//}

		//////////////////////////////////////////MODIFICATION/////////////////////////////////////////////		
	    if(!is_null($base_id) && $base_id!=$id){	              	        
									  		      	
	      	echo "<br/>";
		    $khoueiry = "SELECT * FROM \"PROMOTER\" WHERE \"PROMOTER_ID\"=".$base_id.";";	
			$stmt = pg_query($c,$khoueiry);
			if($row=pg_fetch_array($stmt)){	      
			    print "&nbsp;&nbsp;Modification of <a href=\"reg-region-edit.php?id=".$base_id."\" target=\"_blank\">".$row["NAME"]."</a>";			    		
				print "<br />&nbsp;&nbsp;&nbsp;&nbsp; By deletion: ";  	    
			    if($deletion=="y"){	            
			      	print "<a target=\"_BLANK\" href=\"reg-region-edit-modif.php?id=".$id."&deletion=n&mutation=".$mutation."&addition=".$addition."&is_natural=$is_natural\"><img border=\"0\" width=\"25\" title=\"Switch\" src=\"pictures/button-cur-validate.gif\"></a>";
				} else {
			      	print "<a target=\"_BLANK\" href=\"reg-region-edit-modif.php?id=$id&deletion=y&mutation=$mutation&addition=$addition&is_natural=$is_natural\"><img border=\"0\" width=\"25\" title=\"Switch\" src=\"pictures/button-cur-delete.gif\"></a>";				  	
				}
			    print "<br />&nbsp;&nbsp;&nbsp;&nbsp; By mutation(s): ";  
				if($mutation=="y"){				  
			      	print "<a target=\"_BLANK\" href=\"reg-region-edit-modif.php?id=$id&deletion=$deletion&mutation=n&addition=$addition&is_natural=$is_natural\"><img border=\"0\" width=\"25\" title=\"Switch\" src=\"pictures/button-cur-validate.gif\"></a>";				  
				} else {
			      	print "<a target=\"_BLANK\" href=\"reg-region-edit-modif.php?id=$id&deletion=$deletion&mutation=y&addition=$addition&is_natural=$is_natural\"><img border=\"0\" width=\"25\" title=\"Switch\" src=\"pictures/button-cur-delete.gif\"></a>";				  
				}
			
				print "<br /> &nbsp;&nbsp;&nbsp;&nbsp; By other artificial modification: ";  					  
				if($addition=="y"){
			      	print "<a target=\"_BLANK\" href=\"reg-region-edit-modif.php?id=$id&deletion=$deletion&mutation=$mutation&addition=n&is_natural=$is_natural\"><img border=\"0\" width=\"25\" title=\"Switch\" src=\"pictures/button-cur-validate.gif\"></a>";						
				} else {
			      	print "<a target=\"_BLANK\" href=\"reg-region-edit-modif.php?id=$id&deletion=$deletion&mutation=$mutation&addition=y&is_natural=$is_natural\"><img border=\"0\" width=\"25\" title=\"Switch\" src=\"pictures/button-cur-delete.gif\"></a>";					  
				}
			    print '<br/><br/>';
			}
		}	
		
		print "<a target=\"_BLANK\" href=\"reg-region-edit-comments.php?id=$id\"><img border=\"0\" width=\"25\" title=\"Edit Comments\" src=\"pictures/button-cur-edit.gif\"></a><strong>Comments:</strong><br/>".$comments."<br/>";
		        
		/////////////////////////////HIERARCHY/////////////////////////////////////////////
		echo "<br/>";
		//if ($rtest["IS_ADMIN"]=='y') {
			//add an edit link here...
			print "<a target=\"_BLANK\" href=\"reg-region-edit-hierarchy.php?id=$id\"><img border=\"0\" width=\"25\" title=\"Edit Parent\" src=\"pictures/button-cur-edit.gif\"></a>";
		//}
		echo "<u><strong><font size=\"+2\">Hierarchy of Regulatory Regions:</font></strong></u><br/><br/>";
	        
	    //find the main root and then print the whole hierarchy... 
		//this way it is more uniform...
	    $root = findroot($c,$id);
		if($root !== null){
			printhierarchy($c,$id,$root,0);					
		} else {
			echo "<u><strong><font size=\"+2\">There is a loop in the hierarchy of Regulatory Regions - please correct it!:</font></strong></u><br/><br/>";
		}
		echo '<br/>';		        
	
		/////////////////////////////FEATURES///////////////////////////////////////////////
		/*	
	    print "<u><strong><font size=\"+2\">Features:</font></strong></u><br><br>";
		print "<a target=\"_BLANK\" title=\"Change name\" href=\"curator-mol-edit.php?type=promoter&part=name&id=$id\"><img border=\"0\" src=\"pictures/button-cur-edit.gif\"></a><strong>Name: </strong>".$name."<br>";		
		print "<a target=\"_BLANK\" href=\"reg-region-coord-edit.php?id=$id&begin=$begin&end=$end\"><img border=\"0\" src=\"pictures/button-cur-edit.gif\"></a><strong>ANISEED Coordinates: </strong>[".$begin." / ".$end."]<br>";
		
        print "<a target=\"_BLANK\" href=\"curator-mol-edit.php?type=promoter&part=comments&id=$id\"><img border=\"0\" src=\"pictures/button-cur-edit.gif\"></a><strong>Comments:</strong>".$comments."<br/>";
       	*/        						
		
		///////////////////////////////////////TYPE OF REGULATION///////////////////////////////////////////////
		if($type==NULL){
			$type = "(not defined)";
		}
		print "<br /><a href=\"reg-region-edit-type.php?id=$id\" target=\"_blank\"><img src=\"pictures/button-cur-edit.gif\" border=\"0\" width=\"25\" title=\"Edit type of regulatory activity\"></a><strong><u><font size=\"+2\">Type of Regulation:</font></u> ".$type."</strong><br/>";		
		
		///////////////////////////////////////REGULATED GENES///////////////////////////////////////////////
		print "<br><u><strong><font size=\"+2\">Regulated genes:</font></strong></u>
		&nbsp;<a href=\"reg-region-gene-add.php?id=$id\" target=\"_blank\"><img src=\"pictures/button-cur-add.jpg\" width=\"20\" border=\"0\" title=\"Add a new regulated gene\"></a><br/><br/>";
		$khoueiry="select a.\"NAME\", a.\"GENE_ID\", b.\"TYPE\" from \"GENE\" a, \"GENE_REGULATION\" b where (b.\"PROMOTER_ID\"='$id') and (a.\"GENE_ID\"=b.\"GENE_ID\")";
		$stmt = pg_query($c,$khoueiry);
		$count=0;
		while($row=pg_fetch_array($stmt)){
		    ++$count;
		    //print "<a href=\"reg-region-gene-delete.php?id=".$id."&geneid=".$row["GENE_ID"]."\" target=\"_blank\"><img src=\"pictures/button-cur-delete.gif\" width=\"20\" border=\"0\" title=\"Delete this regulated gene\"></a> <strong>Regulated gene: &nbsp;&nbsp;</strong> <a href=\"molecule-gene.php?name=".$row["NAME"]."\">".$row["NAME"]."</a> ".$row["TYPE"]."<br/>";
		    print "<a href=\"reg-region-gene-delete.php?id=".$id."&geneid=".$row["GENE_ID"]."\" target=\"_blank\"><img src=\"pictures/button-cur-delete.gif\" width=\"25\" border=\"0\" title=\"Delete this regulated gene\"></a> <strong>Regulated gene: &nbsp;&nbsp;</strong> <a href=\"molecule-gene.php?name=".$row["NAME"]."\">".$row["NAME"]."</a><br/>";		    
		}
		if($count==0) print "No regulated genes<br>";


		///////////////////////////////////////CONSTRUCTS//////////////////////////////////////////////////////
		print "<br><u><strong><font size=\"+2\">Constructs made to test this region:</font></strong></u> 
			&nbsp;<a href=\"reg-region-construct-add.php?promid=$id\" target=\"_blank\"><img src=\"pictures/button-cur-add.jpg\" width=\"20\" border=\"0\" title=\"Create a new construct\"></a>
			<br/><br/>";	
			
		$khoueiry="SELECT * FROM \"CONSTRUCTION\" WHERE \"PROMOTER_ID\"=$id;";
		$stmt = pg_query($c,$khoueiry);
		$count=0;
		while($row=pg_fetch_array($stmt)){		  
		    ++$count;		    			
			
	    	print "<a href=\"reg-region-construct-delete.php?id=".$row["CONSTRUCTION_ID"]."\" target=\"_blank\"><img src=\"pictures/button-cur-delete.gif\" width=\"25\" border=\"0\" title=\"Delete this construct\"></a> 
			Construct ".$row["STABLE_ID"].": <a href=\"construct-edit.php?constructid=".$row["CONSTRUCTION_ID"]."\" target=\"_blank\">".$row["NAME"]."</a> <a href=\"insitu-result.php?target=".$row["STABLE_ID"]."&MOLtype=1\" target=\"_blank\"> <img src=\"pictures/button-getPics.jpg\" width=\"70\" border=\"0\" title=\"View Insitu data\"></a> <br />";
			
		}

		if($count==0) { 		  
			print "No constructs<br/>";	
		} else {
		   //SHOW GLOBAL_IN_SITU
		}
		
		///////////////////////////////////////SEQUENCE OVERVIEW///////////////////////////////////////////////
		
		print "<br><u><strong><font size=\"+2\">Overview of the regulatory motifs in this sequence:</font></strong></u>";
		//print the graphical display with motifs...
		if($length>0){
			print '<br/><br/><strong>'.$begin.'</strong><img src="reg-region-draw.php?width='.$max_width.'&id='.$id.'" border=0></img><strong>'.$end.'</strong>';  
		}						
		print '<br/>';							 
		
		///////////////////////////////////////REGULATORY MOTIFS///////////////////////////////////////////////		
		print "<br><u><strong><font size=\"+2\">Regulatory motifs:</font></strong></u> 
			&nbsp;<a href=\"reg-region-add-motif.php?regid=$id\" target=\"_blank\"><img src=\"pictures/button-cur-add.jpg\" width=\"20\" border=\"0\" title=\"Add a new motif\"></a><br>";
		
		$khoueiry="select A.\"MOTIF_COORD_ID\", A.\"SEQUENCE\", A.\"MOTIF_ID\", A.\"BEGIN\", A.\"STOP\", A.\"ORIENTATION\", A.\"UPDATE_MATRIX\", B.\"NAME\", A.\"COMMENTS\", B.\"RGB_RED\", B.\"RGB_GREEN\", \"RGB_BLUE\" from \"MOTIF_COORD\" A, \"MOTIF_REGUL\" B where A.\"MOTIF_ID\"=B.\"MOTIF_ID\" and A.\"PROMOTER_ID\"=$id order by A.\"BEGIN\" ";
		$stmt = pg_query($c,$khoueiry);
		$motif_list = array();
		$count++;
		while($row=pg_fetch_array($stmt)){
			$motif_list[count($motif_list)] = $row;
		    $count++;	
		}
		
		foreach($motif_list as $pos => $data){
			
			$pos++;
			$row = $data;			
		
			print "<br> <a href=\"reg-region-delete-motif.php?id=".$row["MOTIF_COORD_ID"]."&regid=$id\" target=\"_blank\"><img src=\"pictures/button-cur-delete.gif\" width=\"25\" border=\"0\" title=\"Delete this motif\"></a> <i>Motif $pos :</i>&nbsp; ".$row["SEQUENCE"]." <br>";
	    
	    //print "<strong>Name: &nbsp;&nbsp;</strong> ".$row["NAME"]."&nbsp;&nbsp;<a href=\"edit-motif-name.php?name=$name&motif=".$row["MOTIF_ID"]."&begin=".$row["BEGIN"]."&moname=".$row["NAME"]."\" target=\"_blank\"><img src=\"pictures/button-cur-edit.gif\" width=\"25\" border=\"0\" title=\"Edit\"></a><br>";
			print "<a href=\"reg-region-motif-edit-type.php?id=".$row["MOTIF_COORD_ID"]."&motifid=".$row["MOTIF_ID"]."\" target=\"_blank\"><img src=\"pictures/button-cur-edit.gif\" width=\"25\" border=\"0\" title=\"Edit this motif\"></a>&nbsp;&nbsp;<strong>Type: &nbsp;&nbsp; </strong> <a href=\"motif-edit.php?id=".$row["MOTIF_ID"]."\" target=\"_blank\">".$row["NAME"]."</a> <br/>";
            
        //Show the edit position...
			print "<a href=\"reg-region-motif-edit-position.php?id=".$row["MOTIF_COORD_ID"]."&begin=".$row["BEGIN"]."&stop=".$row["STOP"]."&promoter=$id\" target=\"_blank\"><img src=\"pictures/button-cur-edit.gif\" width=\"25\" border=\"0\" title=\"Edit\"></a>&nbsp;&nbsp;<strong>Position: </strong> [".$row["BEGIN"]." / ".$row["STOP"]."]<br>";
	    //print "<strong>Position: </strong> [".$row["BEGIN"]." / ".$row["STOP"]."]&nbsp;&nbsp;<br>";
		//print "<strong>Sequence: </strong> ".$row["SEQUENCE"]."<br/>"; 
		
		/*
		//Show the update matrix button...
		//print "<strong>Motif Orientation: </strong>".$row["ORIENTATION"]." &nbsp;&nbsp;<a href=\"motif-orientation.php?motif=".$row["MOTIF_ID"]."&begin=".$row["BEGIN"]."&stop=".$row["STOP"]."&orientation=".$row["ORIENTATION"]."&promoter=".$id."&update=".$row["UPDATE_MATRIX"]."\" target=\"_blank\"><img src=\"pictures/button-change.gif\" width=\"25\" border=\"0\" title=\"Edit this motif\"></a> <br/>"; 
		print "<strong>Motif Orientation: </strong>".$row["ORIENTATION"]."<br/>"; 
		
		//show the switch orientation matrix button...
		//print "<strong>Used to update the motif matrix: </strong>".$row["UPDATE_MATRIX"]." &nbsp;&nbsp;<a href=\"motif-update-matrix.php?motif=".$row["MOTIF_ID"]."&begin=".$row["BEGIN"]."&stop=".$row["STOP"]."&update=".$row["UPDATE_MATRIX"]."&promoter=".$id."&orientation=".$row["ORIENTATION"]."\" target=\"_blank\"><img src=\"pictures/button-change.gif\" width=\"25\" border=\"0\" title=\"Edit this motif\"></a><br/>";
		print "<strong>Used to update the motif matrix: </strong>".$row["UPDATE_MATRIX"]."<br/>";
		
		//Enable editing this... MATRIX_SEQ_BEGIN
		print "<strong>Sequence used for the motif matrix: </strong> ".$row["MATRIX_SEQUENCE"]."&nbsp;&nbsp;<a href=\"edit-motif-matrix_seq_begin.php?motif=".$row["MOTIF_ID"]."&begin=".$row["MATRIX_SEQ_BEGIN"]."&seq=".$row["SEQUENCE"]."\" target=\"_blank\"><img src=\"pictures/button-cur-edit.gif\" width=\"25\" border=\"0\" title=\"Edit\"></a><br>";
		*/	   

			//GENES KNOWN TO BIND THIS PARTICULAR SEQUENCE!
			
			print "Genes that bind to this sequence: <a href=\"reg-region-motif-add-gene.php?id=".$row["MOTIF_COORD_ID"]."\" target=\"_blank\"><img src=\"pictures/button-cur-add.jpg\" width=\"20\" border=\"0\" title=\"Add a new gene that binds to this sequence\"></a><br>";			
			
			$khoueiry="select \"NAME\", \"GENE\".\"GENE_ID\" FROM \"GENE\",\"MOTIF_COORD_GENE\" WHERE \"GENE\".\"GENE_ID\"=\"MOTIF_COORD_GENE\".\"GENE_ID\" AND \"MOTIF_COORD_ID\"=".$row["MOTIF_COORD_ID"];
			$stmt = pg_query($c,$khoueiry);
			
			while($row2=pg_fetch_array($stmt)){
				print "&nbsp;&nbsp;&nbsp;<a href=\"reg-region-motif-gene-delete.php?id=".$row["MOTIF_COORD_ID"]."&geneid=".$row2["GENE_ID"]."\" target=\"_blank\"><img src=\"pictures/button-cur-delete.gif\" width=\"25\" border=\"0\" title=\"Delete this gene\"></a> <strong>Gene: &nbsp;&nbsp;</strong> <a href=\"molecule-gene.php?name=".$row2["NAME"]."\">".$row2["NAME"]."</a> binds to this sequence.<br/>";	
			}
			
			print "<a href=\"reg-region-motif-edit-comments.php?id=".$row["MOTIF_COORD_ID"]."&comments=".$row["COMMENTS"]."\" target=\"_blank\"><img src=\"pictures/button-cur-edit.gif\" width=\"25\" border=\"0\" title=\"Edit\"></a>&nbsp;&nbsp;<strong>Comments: </strong> ".$row["COMMENTS"]."<br/>";								
			
		}
		if($count==0) print "No motifs<br>";				
		
		////////////////////////////////SEQUENCES DERIVED FROM THIS ONE////////////////////////////////////////
/*		
		print "<br /><u><strong><font size=\"+2\">Child Regions: </font></strong></u> 
			&nbsp; <a href=\"reg-region-add-child.php?id=$id\" target=\"_blank\">
			<img src=\"pictures/button-cur-add.jpg\" width=\"20\" border=\"0\" title=\"Create a child region\"></a>
			<br /> <br />";					
		
		//ORDER BY BEGIN AND END...
		//print the name with a link to edit and a basic graphical display with the motifs...
		$khoueiry="SELECT * FROM \"PROMOTER\" WHERE \"BASE_REG_ID\"=$id AND \"PROMOTER_ID\"!=$id ORDER BY \"BEGIN\"";
		$stmt = pg_query($c,$khoueiry);
		$cmodif=0;
		$modif_list = array();
		while($row=pg_fetch_array($stmt)){
		    ++$cmodif;		  
			$modif_list[]=$row;
		}		
		
		if($cmodif==0) { 
			print "No child regions"; 
		} else {
		  	foreach($modif_list as $cmodif){
	 	   		print "<a href=\"reg-region-edit.php?id=".$cmodif["PROMOTER_ID"]."\">".$cmodif["NAME"]."</a>";
	   			//new width... according BEGIN / END
	   			if($cmodif["DELETION"]=='y'){
				     echo ' (deletion) ';
				}
				if($cmodif["MUTATION"]=='y'){
				     echo ' (mutation) ';
				}
				if($cmodif["ADDITION"]=='y'){
				     echo ' (artificial modification) ';
				}				
				print '<br/><br/><strong>'.$cmodif["BEGIN"].'</strong><img src="reg-region-draw.php?width='.$max_width.'&id='.$cmodif["PROMOTER_ID"].'&nbrs=false" border=0></img><strong>'.$cmodif["END"].'</strong><br/><br/>';   
			}
		}		
			
*/		
	//////////////////////////////////////////SEQUENCE/////////////////////////////////////////////
	
	//TODO Adjust to be just one sequence....
	$khoueiry="select \"SEQUENCE\", \"LENGTH\", \"COMMENTS\", \"MOL_ID\" from \"SEQUENCE\" where \"MOL_ID\"=$id";
	$stmt = pg_query($c,$khoueiry);
		
	if($row=pg_fetch_array($stmt)){
		$lob = $row["SEQUENCE"];

		pg_query ($c, "begin");		
		$handle_lo = pg_lo_open($c,$lob,"r");
		$seq=pg_lo_read($handle_lo);
		pg_query($c,"end");
					
		$seq=ereg_replace("\n","",$seq);
		
		$motif_seq = '';
		$mtf = 0;
		$count_seventy = 0;
		if(count($motif_list)>0){
		
			for($i=0;$i<strlen($seq);$i++){
		
				$count_seventy++;
				if($count_seventy==70){
					$motif_seq.="\n";
					$count_seventy=1;
				}
			
				$motif = $motif_list[$mtf];
				$motif_pos_a = $motif["BEGIN"] - $begin;
				if(($motif["BEGIN"]*$begin)<0){ $motif_pos_a = $motif_pos_a - 1; }		  	
				$motif_pos_b = $motif["STOP"] - $begin;
				if(($motif["STOP"]*$begin)<0){ $motif_pos_b = $motif_pos_b - 1; }	
			
				//COLOR...
				$red = dechex($motif["RGB_RED"]);
				if(strlen($red)==1) {$red='0'.$red;}
				$green = dechex($motif["RGB_GREEN"]);
				if(strlen($green)==1) {$green='0'.$green;}
				$blue = dechex($motif["RGB_BLUE"]);
				if(strlen($blue)==1) {$blue='0'.$blue;}
				$color = strtoupper($red.$green.$blue);
			
				#normal case... just print the character...
				if(!($i==$motif_pos_a) && !($i==$motif_pos_b)){
					$motif_seq.=substr($seq,$i,1);
				}
			
				#we hit a motif!... so we open the motif color
				if($i==$motif_pos_a){
					$motif_seq.="<font color=\"#$color\"><strong>".substr($seq,$i,1);
				}
			
				#we hit the end of the current motif... so we close the color
				if($i==$motif_pos_b){
					$motif_seq.=substr($seq,$i,1)."</font></strong>";
								
					#now check for overlaps...							
					$next_motif_pos_b = -1;	
					$next_motif_pos_a = $i;
					while($i>=$next_motif_pos_b && $mtf < (count($motif_list)-1)){
						$mtf++;
						$next_motif = $motif_list[$mtf];
						$next_motif_pos_a = $next_motif["BEGIN"] - $begin;
						if(($next_motif["BEGIN"]*$begin)<0){ $next_motif_pos_a = $next_motif_pos_a - 1; }		  	
						$next_motif_pos_b = $next_motif["STOP"] - $begin;
						if(($next_motif["STOP"]*$begin)<0){ $next_motif_pos_b = $next_motif_pos_b - 1; }
				
						//COLOR...
						$red = dechex($next_motif["RGB_RED"]);
						if(strlen($red)==1) {$red='0'.$red;}
						$green = dechex($next_motif["RGB_GREEN"]);
						if(strlen($green)==1) {$green='0'.$green;}
						$blue = dechex($next_motif["RGB_BLUE"]);
						if(strlen($blue)==1) {$blue='0'.$blue;}
						$color = strtoupper($red.$green.$blue);	
					
									#after removing overlaps									
						if($i>=$next_motif_pos_a && $i<$next_motif_pos_b){
							$motif_seq.="<font color=\"#$color\"><strong>";
						}
					}												
				}		
			}
		} else {
			$motif_seq = chunk_split($seq, 70, "\n");
		}
/*		
	//old version wasn't working... as soon as tests confirm the new version is working delete this!
		$seq = chunk_split($seq, 70, "\n");
		
	    $motif_seq = '';
	    $pos = 0;
	    
	    $found_trouble = false;
	    $mtf = 0;	    
	    //foreach($motif_list as $motif){		
	    while($mtf<count($motif_list)){
	        $motif = $motif_list[$mtf];

			if(($motif["BEGIN"] < $begin) || ($motif["STOP"] > $end)){
			 	$found_trouble = true;
				$mtf++;
				continue;  
			} else {
			  	//Position 0 does not exist
				$motif_pos_a = $motif["BEGIN"] - $begin;
				if(($motif["BEGIN"]*$begin)<0){ $motif_pos_a = $motif_pos_a - 1; }		  	
				$motif_pos_b = $motif["STOP"] - $begin;
				if(($motif["STOP"]*$begin)<0){ $motif_pos_b = $motif_pos_b - 1; }				
			
				$motif_pos_a = $motif_pos_a + floor($motif_pos_a / 70);
				$motif_pos_b = $motif_pos_b + floor($motif_pos_b / 70);			
												
				//COLOR...
				$red = dechex($motif["RGB_RED"]);
				if(strlen($red)==1) {$red='0'.$red;}
				$green = dechex($motif["RGB_GREEN"]);
				if(strlen($green)==1) {$green='0'.$green;}
				$blue = dechex($motif["RGB_BLUE"]);
				if(strlen($blue)==1) {$blue='0'.$blue;}
				$color = strtoupper($red.$green.$blue);
				$length_to_next_motif = ($motif_pos_a) - $pos + floor(($motif_pos_a-$pos) / 70);
				$motif_seq = $motif_seq.substr($seq,$pos,$length_to_next_motif)."<font color=\"#$color\"><strong>";
				
				echo "Adding before motif ".$length_to_next_motif." bps: <br/><pre>".substr($seq,$pos,$length_to_next_motif)."</pre><br/>";	
			
				$motif_length = $motif_pos_b - $motif_pos_a + 1;
				$pos = $motif_pos_a;									
				$motif_seq = $motif_seq . substr($seq,$pos,$motif_length) . "</strong></font>";
				
				echo "Motif ".$mtf.": ".$motif_pos_a. " - ".$motif_pos_b."<br/>";
				echo "Adding motif ".$motif_length.": <br/><pre>".substr($seq,$pos,$motif_length)."</pre><br/>";	
				
				$pos = $pos + $motif_length;
			
				//deal with overlapping motifs!
				while(isset($motif_list[$mtf+1]) && ($motif_list[$mtf+1]["STOP"]<=$motif_list[$mtf]["STOP"])){
					  $mtf++;				  
				} 
				if(isset($motif_list[$mtf+1]) && ($motif_list[$mtf+1]["BEGIN"]<$motif_list[$mtf]["STOP"])){
					$motif_list[$mtf+1]["BEGIN"]=$motif_list[$mtf]["STOP"]+1;	  
				}
						
				$mtf++;			 	 
			}
			
		}
		$motif_seq = $motif_seq . substr($seq,$pos);
*/

		print "<br/><br/><a target=\"_BLANK\" href=\"reg-region-coord-edit.php?id=$id&begin=$begin&end=$end\"><img border=\"0\" width=\"25\" src=\"pictures/button-cur-edit.gif\"></a><strong><font size=\"+2\">ANISEED Coordinates: </font></strong>[".$begin." / ".$end."]<br/>";
		
		print "<br/><a href=\"sequence-edit.php?id=$id\" target=\"_blank\"><img src=\"pictures/button-cur-edit.gif\" width=\"25\" border=\"0\" title=\"Edit\"></a><u><strong><font size=\"+2\">Sequence</font></strong></u><br/>";

		print "<strong>Length: </strong>".$row["LENGTH"]."<br/>";		
		print $row["COMMENTS"]."<br/>";		

		//////////////////////////////////////////SEQUENCE WITH MOTIFS/////////////////////////////////////////////
		print "<pre><font face=\"Courier New, Courier, mono\" size=\"3\">".strtoupper($motif_seq)."</font></pre>";
		
		}
		else
		{
		print "<br><br><a href=\"sequence-edit.php?id=$id\" target=\"_blank\"><img src=\"pictures/button-cur-edit.gif\" width=\"25\" border=\"0\" title=\"Edit\"></a><u><strong><font size=\"+2\">Sequence</font></strong></u><br></pre>";
		}
	
	if($found_trouble){
		echo "<strong>Warning: </strong> Coordinates of some motifs do not agree with region coordinates!";
	}


		//////////////////////////////////////REFERENCES////////////////////////////////////////////////////////
		print "<br><u><strong><font size=\"+2\">References:</font></strong></u> 
		&nbsp;<a href=\"addreferencebyparsing.php?id=$id\" target=\"_blank\"><img src=\"pictures/button-cur-add.jpg\" width=\"20\" border=\"0\" title=\"Add a new Reference\"></a>
		<br/>";
		
		$khoueiry="SELECT * FROM \"REFERENCE\" WHERE \"BIO_ID\"=$id;";
		$stmt = pg_query($c,$khoueiry);
		$count=0;
		//while($row=pg_fetch_array($stmt) && !is_null($row["PUBMED_ID"])){
		while($row=pg_fetch_array($stmt)){
			if(!is_null($row["PUBMED_ID"])) {
				++$count;

				print "<br/><a href=\"deletereference.php?id=$id&pubmedid=".$row["PUBMED_ID"]."\" target=\"_blank\"><img src=\"pictures/button-cur-delete.gif\" width=\"25\" border=\"0\" title=\"Delete this reference\"></a><strong>Reference: </strong> ".$row["AUTHORS"].". ".$row["TITLE"].".&nbsp;&nbsp; PUBMED ID: <a href=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=pubmed&dopt=Abstract&list_uids=".$row["PUBMED_ID"]."\" target=\"_blank\"> ".$row["PUBMED_ID"]." </a><br/>";            
			}
		}
		if($count==0) print "No references<br>";   	  

///////////////////////////////////////////////////////END		
	}else{
		print "<br><br><center><h2><strong>No match</strong></h2></center><br><br>";
	}

	include ("frames_footer.php"); 

?>