
<?php

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

	if ( (!isset($_SESSION["login"]))or(!isset($_SESSION["pass"])) ) {
	    print "<strong>you need to <a href=\"login.php\">login</a> as an authorised curator to proceed.</strong>";
	    print '</center></body></html>';
		return;
	}

    $id=$_POST["ID"];
    $lob=$_POST["LOB_ID"];
    $comments = $_POST["COMMENTS"];

	$replace = array(" ","\t","\n","\r");
	$_POST["SEQUENCE"] = str_replace($replace, "", $_POST["SEQUENCE"]); 


	pg_query ($c, "BEGIN") or die("<strong>MYERROR </strong>".pg_last_error($c));
	
	$length = strlen($_POST["SEQUENCE"]);		
//MODIFICATION : adding of the condition to test if there is already a sequence in the databse for this mol_id
if (strlen($lob)>0) pg_lo_unlink($c,$lob);
	$lob_id = pg_lo_create($c);
	
//ADDING of condition on the lob size, if the size equals 0, that's an insert cause the sequence is not present in 
// the database, else that's an update ...

if (strlen($lob)==0)
	{
	$query="INSERT INTO \"SEQUENCE\" (\"MOL_ID\",\"SEQUENCE\",\"LENGTH\",\"COMMENTS\") 
			values ('$id','$lob_id','$length','$comments');";
	if(!pg_query($c,$query)){
		$success = false;
		echo '<p>Error inserting SEQUENCE<p>';
		}

	}
else {
	$khoueiry = "UPDATE \"SEQUENCE\" SET \"SEQUENCE\" = $lob_id,\"COMMENTS\"='$comments', \"LENGTH\"=$length WHERE \"MOL_ID\"=$id;";
print $khoueiry."<br>";
	if(!pg_query($c,$khoueiry)){
		$success = false;
		echo '<p>Error updating SEQUENCE<p>';
		}
}
						
    $lob_handle = pg_lo_open($c, $lob_id, "w");    
    if(pg_lo_write($lob_handle, $_POST["SEQUENCE"])===FALSE){
		$success = false;	  
	}
    pg_lo_close($lob_handle);   	
    
	$khoueiry="SELECT * FROM \"PROMOTER\" WHERE \"PROMOTER_ID\"=$id";		
	$stmt = pg_query($c,$khoueiry);
	if($row=pg_fetch_array($stmt)){
		$begin = $row["BEGIN"];
		
		//0 does not exist!
		$add=0;
		if(($begin<0) && ($begin+$length>=0)){ $add = 1; }
		$khoueiry = "UPDATE \"PROMOTER\" SET \"END\" = ".($begin+$length+$add)." WHERE \"PROMOTER_ID\"=$id;";
		if(!pg_query($c,$khoueiry)){
			$success = false;
			echo '<p>Error updating PROMOTER<p>';
		}
	}			

	$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'){
	      $khoueiry = "update \"ENTRY_ORIGIN\" set \"CURATOR_ID\"=".$_SESSION['curationauthor'].", \"CURATION_DATE\"=now() where \"BIO_ID\"='$id'";	  
	} else {
	      $khoueiry = "update \"ENTRY_ORIGIN\" set \"ANNOTATOR_ID\"=".$_SESSION['curationauthor'].", \"ANNOTATION_DATE\"=now() where \"BIO_ID\"='$id'";		  
	}
	pg_query($c,$khoueiry) or die("<strong>ERROR </strong>".pg_last_error($c));
	
	pg_query($c,"COMMIT") or die("<strong>ERROR </strong>".pg_last_error($c));
	
	echo '<SCRIPT LANGUAGE="JavaScript"> javascript:opener.location.reload(); self.close(); </script>';	
	include ("frames_footer.php");
	
?>