<?php
/*
* track.php
* http://tasuke.dna.affrc.go.jp/
*
* Author: Ryutaro Itoh
*
* Copyright (c) 2013 National Institute of Agrobiological Sciences
*
* This software is released under the MIT License.
*
* http://opensource.org/licenses/mit-license.php
*/

require '../conf/config.php';
require './common.php';
////////////////////////////////// Connecting with DB
if( !$conn = new mysqli($host, $user, $pswd, $db)) {
    error_log("Connection failed.\n");
    exit;
}

////////////////////////////////// Parameters
$prm_Tracks=array();
(isset($_GET['prm_Zoom']) && !empty($_GET['prm_Zoom'])) ? $prm_Zoom=$_GET['prm_Zoom']:returnError("Error");
(isset($_GET['prm_Chr']) && !empty($_GET['prm_Chr'])) ? $prm_Chr=$_GET['prm_Chr']:returnError("Error");
(isset($_GET['prm_Pos']) && !empty($_GET['prm_Pos'])) ? $prm_Pos=$_GET['prm_Pos']:returnError("Error");
(isset($_GET['prm_Block']) && !empty($_GET['prm_Block'])) ? $prm_Block=$_GET['prm_Block'] : returnError("Error");
(isset($_GET['prm_Track']) && !empty($_GET['prm_Track'])) ? $prm_Track=$_GET['prm_Track'] : returnError("Error");
if(!_validate_chrs($conn,$prm_Chr)){exit;}
if (!(is_numeric($prm_Pos)) || !(is_numeric($prm_Block))) {
	$errmsg = "<div align=\"center\"><font color=\"red\" style=\"font-size:18px;\">Invalid Value!!</font></div>";
        echo $errmsg;
        exit;
}
_pregMatch($prm_Track);
if(preg_match("/\;|\||\&|\`|\(|\)|\<|\>|\*|\?|\{|\}|\[|\]|\!/",$prm_Zoom)) {
	$prm_Zoom = "1k";
}
$db_range_start=$prm_Pos*_cvtZoom($prm_Zoom)-_cvtZoom($prm_Zoom);
$db_range_end=($prm_Pos+$prm_Block)*_cvtZoom($prm_Zoom);
$prm_Tracks = explode("---SPL---",$prm_Track);
///////////////////////////////////////////////////////////////////////////////
// draw Primer3 Track
///////////////////////////////////////////////////////////////////////////////
$start = ""; //$rowN2
$end = ""; //$rowN3
$secstart = ""; //$rowS0
$secend = "";
$idsArr=array();
for($i=0;$i<count($prm_Tracks);$i++) {
	$prminfos = explode("---TRK---",$prm_Tracks[$i]);
	if($prminfos[0] == "all") {
		$start = $prminfos[1];
		$end = $prminfos[2];
		$a1=0;
		$a2=0;
		$a3=0;
		$rtnArr=array();
		if ( $prm_Zoom == "1b" ) {
			$rs=((int)$start/_cvtZoom($prm_Zoom))-$prm_Pos;
        		$re=((int)$end/_cvtZoom($prm_Zoom))-$prm_Pos;
        		$p1=(int)((int)$start/_cvtZoom($prm_Zoom))-$prm_Pos;
        		if ((int)$end%_cvtZoom($prm_Zoom)){
        	    		$p=(int)((int)$end/_cvtZoom($prm_Zoom))-$prm_Pos+1;
        		} else {
            	   		 $p=(int)((int)$end/_cvtZoom($prm_Zoom))-$prm_Pos;
        		}
		}else{
        		$rs=((int)$start/_cvtZoom($prm_Zoom))-$prm_Pos+1;
        		$re=((int)$end/_cvtZoom($prm_Zoom))-$prm_Pos+1;
        		$p1=(int)((int)$start/_cvtZoom($prm_Zoom))-$prm_Pos+1;
        		if ((int)$end%_cvtZoom($prm_Zoom)){
        	    		$p=(int)((int)$end/_cvtZoom($prm_Zoom))-$prm_Pos+2;
        		} else {
        	    		$p=(int)((int)$end/_cvtZoom($prm_Zoom))-$prm_Pos+1;
        		}
		}

		if ( $p1 > $a1 || $a1 == null ) {
        		$h=1;
        		$a1=$p;
		} else if ( $p1 > $a2 || $a2 == null ) {
	        	$h=2;
        		$a2=$p;
		} else if ( $p1 > $a3 || $a3 == null ) {
	        	$h=3;
	        	$a3=$p;
		} else {
	        	$h=4;
		}
		$arrStr="[{\"id\":\"Primer3 Result\",\"name\":\"Peimer3 Result\",\"pos\":\"".(int)$start."\",\"length\":\"".(int)($end-$start+1)."\",\"strand\":\"\",\"s\":\"".$p1."\",\"e\":\"".$p."\",\"h\":\"".$h."\",\"rs\":\"".$rs."\",\"re\":\"".$re."\",\"ln\":\"\"";
	} else {
		$secstart = $prminfos[1]; //$rowS0
                $secend = $prminfos[2]; 
		$s=($secstart-$start)/($end-$start+1)*100;
		$l=($secend-$secstart+1)/($end-$start+1)*100;
		//$idsArr=array();
		$idsArr[]=$prminfos[0]."-".$s."-".$l;
	}
}
$subStr=",\"t\":\"";
if ( count($idsArr) ) {
	for($j=0;$j<count($idsArr);$j++){
        	$subStr=$subStr.$idsArr[$j];
                if($j<count($idsArr)-1){$subStr=$subStr.";";}
            	//$subStr=$subStr."\"";
        }
	$arrStr=$arrStr.$subStr."\"}]";
}
echo $arrStr;

///////////////////////////////////////////////////////////////////////////////
// Loading FASTA during zoom is '1b'
///////////////////////////////////////////////////////////////////////////////
/*
if ( $prm_Zoom == '1b' ) {
    $prm_Chr = $conn->real_escape_string($prm_Chr);
    $queryFa = "SELECT ".$prm_Chr."_f FROM sys_fasta WHERE pos>=? AND pos<? ";
    $stmtFa = $conn->stmt_init();
    $stmtFa->prepare($queryFa);
    $paramFa1=($prm_Pos+$prm_Block);
    $stmtFa->bind_param("ii", $prm_Pos, $paramFa1);
    $stmtFa->execute();
    $stmtFa->store_result();
    $stmtFa->bind_result($rowF0);
    while ($stmtFa->fetch()) {
        $arrF[]="{\"f\":\"".$rowF0."\"}";
    }
    $stmtFa->free_result();
    $stmtFa->close();
    $rtnString=$rtnString."|[";
    for($i=0;$i<count($arrF);$i++){
        $rtnString=$rtnString.$arrF[$i];
        if($i<count($arrF)-1){$rtnString=$rtnString.",";}
    }
    $rtnString=$rtnString."]";
} else {
    $rtnString=$rtnString."|[]";
}

echo $rtnString;
*/
function returnError($str){
    echo $str;
}

function _cvtZoom($str) {
    preg_match("/^[0-9]+/", $str, $r1);
    preg_match('/[b,k]$/', $str, $r2);
    $v=$r1[0];
    if($r2[0] == "b"){
        $r=1*(int)$v;
    } else {
        $r=1000*(int)$v;
    }
    return (int)$r;
}

function _validate_chrs($conn, $prm_Chr){
    $flag = false;
    $query = "select seq from sys_chromosome where id=? limit 1";
    $stmt = $conn->stmt_init();
    $stmt->prepare($query);
    $stmt->bind_param("s", $prm_Chr);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($row0);
    while ($stmt->fetch()) {
        $flag = true;
    }
    $stmt->free_result();
    $stmt->close();
    if($flag){
       return true;
    }else{
       return false;
    }
}

?>
