<?php
	include ("frames_header.php"); 
	
	include("connection.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;
	}
	
	$name = $_POST["NAME"];
	//$size = $_POST["SIZE"];
	$comments = $_POST["COMMENTS"];
	  	
  	pg_query($c, "BEGIN");  

	$khoueiry="INSERT INTO \"BIO_ENTITY\" (\"BIO_ID\", \"CURATED\" ) values ( nextval('\"S_BIO_ID\"'),'n')";	
  	
  	$success = true;
	if(!pg_query($c,$khoueiry)){
	  $success = false;
	  echo '<p>Error inserting BIO_ENTITY</p>';
	} 
	
	//Insert the new Motif...
	//Find a new color, and enter an empty Matrix
	/*
	$mat = "";
	for($time=1;$time<=4;$time++){
		for($length=0;$length<$size;$length++){
		  	if($length<($size-1)){
				$line=$line."\t";
			}			 	 
		}		
		if($line<4){
		  $mat = $mat.$line."\n";
		} else {
		  $mat = $mat.$line;		  
		}				
	}
	*/
	
	//$khoueiry = "INSERT INTO \"MOTIF_REGUL\" (\"MOTIF_ID\",\"NAME\",\"SIZE\",\"TYPE\",\"COMMENTS\",\"MATRIX\", \"RGB_RED\",\"RGB_GREEN\",\"RGB_BLUE\") VALUES (currval('\"S_BIO_ID\"'),'".$name."',".$size.",'manual','".$comments."','".$mat."',".rand(0,255).",".rand(0,255).",".rand(0,255).");";
  	
  	$khoueiry = "INSERT INTO \"MOTIF_REGUL\" (\"MOTIF_ID\",\"NAME\",\"TYPE\",\"COMMENTS\", \"RGB_RED\",\"RGB_GREEN\",\"RGB_BLUE\") VALUES (currval('\"S_BIO_ID\"'),'".$name."','manual','".$comments."',".rand(0,255).",".rand(0,255).",".rand(0,255).");";
  	
	if(!pg_query($c,$khoueiry)){
	  $success = false;
	  echo '<p>Error inserting MOL_ENTITY</p>';
	} 				
		
	if($success){	  	  
	
	    if(!pg_query($c, "COMMIT")){
	  		$success = false;
			echo "<p>Could not COMMIT</p>";
		} else {
			$khoueiry = "SELECT CURRVAL('\"S_BIO_ID\"');";
			$stmt=pg_query($c,$khoueiry); 
  			$cur_prom_id=pg_fetch_result($stmt,0);	    			
  			echo "<p>Motif created!</p>";
  			echo '<META HTTP-EQUIV="Refresh" CONTENT="0; URL=motif-edit.php?id='.$cur_prom_id.'">';
  	    	
		}
	  
	} else {
		echo "<p>Could not create Motif</p>";
	}
		
	include ("frames_footer.php"); 


?>