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

	if ( (!isset($_SESSION["login"]))or(!isset($_SESSION["pass"])) ) {
		include ("frames_header.php");
	    print "<strong>you need to <a href=\"login.php\">login</a> as an authorised curator to proceed.</strong>";
	    include ("frames_footer.php"); 
		return;
	}
	
	echo '<h1>WORK IN PROGRESS</h1>';
	
	$old_abort = ignore_user_abort(true);
		
	$id=$_GET["id"];
	$khoueiry = "SELECT * FROM \"SEQUENCE\" WHERE \"MOL_ID\"=".$id.";";	
	$stmt = pg_query($c,$khoueiry);	
	if($row=pg_fetch_array($stmt)){
	    $comm = $row["COMMENTS"];
	    $lob = $row["SEQUENCE"];		
		pg_query ($c, "begin");		
		$handle_lo = pg_lo_open($c,$lob,"r");
		$seq=pg_lo_read($handle_lo);
		pg_lo_close($handle);
		pg_query($c,"end");	
	}
	

	$tmpoutfname = tempnam("/tmp2/aniseed/", "tmpout");
	$tmpinfname = tempnam("/tmp2/aniseed/", "tmpin");
	
	$handle = fopen($tmpinfname, "w") or die("<strong>ERROR: cannot create file </strong>".pg_last_error($c));	
	fwrite($handle, ">region\n$seq");
	fclose($handle);

	//BLAST
	//$cmd="./BLAST/blastall -p blastn -o $tmpoutfname -i $tmpinfname -e 0.01 -g F -X 20 -m 8 -d ./BLAST/JGIwhole";
	
	//EXONERATE
	//$cmd="./BLAST/exonerate --model affine:local --bestn 1  --percent 85 --showtargetgff no --showalignment no $tmpinfname ./BLAST/cionaV1.masked.fasta > $tmpoutfname";
	//$cmd="./BLAST/exonerate --bestn 1  --showtargetgff no --showalignment no $tmpinfname ./BLAST/cionaV1.masked.fasta > $tmpoutfname";
	//$cmd="./BLAST/exonerate --model est2genome --bestn 1 --gappedextension false --showtargetgff no --showalignment no $tmpinfname ./BLAST/cionaV1.masked.fasta > $tmpoutfname";
	$cmd="./BLAST/exonerate --model est2genome --bestn 1 --showtargetgff no --showalignment no $tmpinfname ./BLAST/cionaV1.masked.fasta > $tmpoutfname";
	
	if(exec($cmd)){
		include("frames_header.php");
	    print "<center>Error checking the position. Check your sequence format</center>";
		include("frames_footer.php");
	    return;
	}	

	$handle = fopen($tmpoutfname, "r") or die("<strong>ERROR: cannot open file </strong>".pg_last_error($c));
	$contents = fread($handle, filesize($tmpoutfname));
	fclose($handle);
	
	unlink($tmpoutfname);	
	unlink($tmpinfname);	

	$lines = explode("\n", $contents);
	$results = explode(" ", $lines[2]);
	
	if(!isset($results[0]) || ($results[0]!=='vulgar:')) { 
		echo '<strong>ERROR: No Match</strong>';
		return;
	} 
	
	$query_id = $results[1];	
    $query_start = $results[2];
    $query_end = $results[3];     
    $query_strand = $results[4];
    $target_id = $results[5];
    $target_start = $results[6];
    $target_end = $results[7];
    $target_strand = $results[8];
    $score = $results[9];

	//process the bloddy thing!!!
	pg_query($c, "BEGIN") or die("<strong>ERROR </strong>".pg_last_error($c)); 
	
	//Erase previous results...
	$khoueiry="DELETE FROM \"PROMOTER_POS\" WHERE \"PROMOTER_ID\"=$id;"; 	  		
	$stmt = pg_query($c,$khoueiry) or die("<strong>ERROR </strong>".pg_last_error($c));
	
	$temp = (array)null;
	for($i=10;$i<count($results);$i++){

		$length = $results[$i+2];
		
		if($results[$i]=='M'){
			
			// PUT IT INTO AN ARRAY FIRST, PROCESS AND THEN INSERT AFTER PROCESSING....
			
			//$khoueiry="INSERT INTO \"PROMOTER_POS\" (\"PROMOTER_ID\", \"LOCAL\", \"BEGIN\", \"END\", \"STRAND\", \"SURE\") VALUES ($id, '".$target_id."', ".$target_start.", ".($target_start+$length).",'".$target_strand ."','n');"; 	
	
			//pg_query($c,$khoueiry) or die("<strong>ERROR </strong>".pg_last_error($c));
			
			$new_insert["LOCAL"] = $target_id;
			$new_insert["BEGIN"] = $target_start;
			$new_insert["END"] = $target_start+$length;
			$new_insert["STRAND"] = $target_strand;
			
			$temp[count($temp)] = $new_insert;
			
			$target_start += ($add + $length + 1);
		}
		if($results[$i]=='I'){
		
			$target_start += ($add + $length + 1);			
		}

		$i+=2;		
		$side = 0;
		$add = 0;
		if($i<count($results) && ($results[$i+1]==3 || $results[$i+1]==5)){
			$side = $results[$i+1];
			$i+=3;
			$add = $results[$i];
		}
		
	}

	$to_insert = (array)null;
	$cur = $temp[0];
	for($i=1;$i<count($temp);$i++){
		$next = $temp[$i];
		if(($next["BEGIN"]-$cur["END"])<3){
			$cur["END"] = $next["END"];
		} else {
			$to_insert[count($to_insert)] = $cur;
			$cur = $next;
		}
	}
	//We have to add the last one!!
	$to_insert[count($to_insert)] = $cur;
	
	foreach ($to_insert as $insert){
		$khoueiry="INSERT INTO \"PROMOTER_POS\" (\"PROMOTER_ID\", \"LOCAL\", \"BEGIN\", \"END\", \"STRAND\", \"SURE\") VALUES ($id, '".$insert["LOCAL"]."', ".$insert["BEGIN"].", ".$insert["END"].",'".$insert["STRAND"] ."','n');"; 	
	
		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>';
	ignore_user_abort($old_abort);
	
 ?> 