<?php

  require '../conf/config.php';

  ////////////////////////////////// Connecting with DB
  $conn = mysql_connect($host, $user, $pswd);
  $db = mysql_select_db($db);

  ////////////////////////////////// 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_Tracks']) && !empty($_GET['prm_Tracks'])) ? $prm_Tracks=$_GET['prm_Tracks'] : returnError("Error");

  $db_range_start=$prm_Pos*_cvtZoom($prm_Zoom)-_cvtZoom($prm_Zoom);
  $db_range_end=($prm_Pos+$prm_Block)*_cvtZoom($prm_Zoom);

  ///////////////////////////////////////////////////////////////////////////////
  // Tracks
  ///////////////////////////////////////////////////////////////////////////////
  $rtnString="";
  for($i=0;$i<count($prm_Tracks);$i++) {
    $query = "SELECT id,name,pos,end+1,(end-pos+1),strand FROM sys_track WHERE track='".$prm_Tracks[$i]."' and chr='".$prm_Chr."' and parent=1 and end+1 >".$db_range_start." and pos <".$db_range_end." order by pos";
    $result=mysql_query($query);

    $a1=0;
    $a2=0;
    $a3=0;
    $rtnArr=array();
    while ($rowN = mysql_fetch_row($result, MYSQL_NUM)) {
		
		if ( $prm_Zoom == "1b" ) {
			$rs=((int)$rowN[2]/_cvtZoom($prm_Zoom))-$prm_Pos;
			$re=((int)$rowN[3]/_cvtZoom($prm_Zoom))-$prm_Pos;
			$p1=(int)((int)$rowN[2]/_cvtZoom($prm_Zoom))-$prm_Pos;
			if ((int)$rowN[3]%_cvtZoom($prm_Zoom)){
				$p=(int)((int)$rowN[3]/_cvtZoom($prm_Zoom))-$prm_Pos+1;
			} else {
				$p=(int)((int)$rowN[3]/_cvtZoom($prm_Zoom))-$prm_Pos;
			}
		}
		else{ 
			$rs=((int)$rowN[2]/_cvtZoom($prm_Zoom))-$prm_Pos+1;
			$re=((int)$rowN[3]/_cvtZoom($prm_Zoom))-$prm_Pos+1;
			$p1=(int)((int)$rowN[2]/_cvtZoom($prm_Zoom))-$prm_Pos;
			if ((int)$rowN[3]%_cvtZoom($prm_Zoom)){
				$p=(int)((int)$rowN[3]/_cvtZoom($prm_Zoom))-$prm_Pos+1;
			} else {
			$p=(int)((int)$rowN[3]/_cvtZoom($prm_Zoom))-$prm_Pos;
			}
		}
      
      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\":\"".$rowN[0]."\",\"name\":\"".$rowN[1]."\",\"pos\":\"".(int)$rowN[2]."\",\"length\":\"".(int)$rowN[4]."\",\"strand\":\"".$rowN[5]."\",\"s\":\"".$p1."\",\"e\":\"".$p."\",\"h\":\"".$h."\",\"rs\":\"".$rs."\",\"re\":\"".$re."\"";

      $idsArr=array();
      if ( $rowN[0] != "" ) {
        $subquery = "SELECT pos, (end-pos+1), type from sys_track where track='".$prm_Tracks[$i]."' and id='".$rowN[0]."' and parent=0 order by pos";
        $ids_result=mysql_query($subquery);
        while ($rowS = mysql_fetch_row($ids_result, MYSQL_NUM)) {
          //$s=round(($rowS[0]-$rowN[2])/$rowN[4]*100);
          //$l=round($rowS[1]/$rowN[4]*100);
          $s=($rowS[0]-$rowN[2])/$rowN[4]*100;
          $l=$rowS[1]/$rowN[4]*100;
          //if ( $l < 1 ) { $l = 1; }
          if ( strstr(strtolower($rowS[2]), "utr") ) {$t="u";}
          else if ( strstr(strtolower($rowS[2]), "cds") ) {$t="c";}
          else {$t="a";}
          $idsArr[]=$t."-".$s."-".$l;
        }
      }

      $subStr="";
      if ( count($idsArr) ) {
        $subStr=",\"t\":\"";
        for($j=0;$j<count($idsArr);$j++){
          $subStr=$subStr.$idsArr[$j];
          if($j<count($idsArr)-1){$subStr=$subStr.";";}
        }
        $subStr=$subStr."\"";
      }

      $arrStr=$arrStr.$subStr."}";
      $rtnArr[]=$arrStr;
    }

    $rtnString=$rtnString."[";
    for($j=0;$j<count($rtnArr);$j++){
      $rtnString=$rtnString.$rtnArr[$j];
      if($j<count($rtnArr)-1){$rtnString=$rtnString.",";}
    }
    $rtnString=$rtnString."]";

    if($i<count($prm_Tracks)-1){$rtnString=$rtnString."|";}

  }

  ///////////////////////////////////////////////////////////////////////////////
  // Loading FASTA during zoom is '1b'
  ///////////////////////////////////////////////////////////////////////////////
  if ( $prm_Zoom == '1b' ) {
    $query = "SELECT ".$prm_Chr."_f FROM sys_fasta WHERE pos>=".$prm_Pos." AND pos<".($prm_Pos+$prm_Block);
    $result=mysql_query($query);
    while ($rowN = mysql_fetch_row($result, MYSQL_NUM)) {
      $arrF[]="{\"f\":\"".$rowN[0]."\"}";
    }
    $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;
  }

?>

