<?php

  //////////////////////////////////  Connecting with DB
  require '../conf/config.php';
  $conn = mysql_connect($host, $user, $pswd);
  $db = mysql_select_db($db);

  //////////////////////////////////  Paramenters
  (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_Mode']) && !empty($_GET['prm_Mode'])) ? $prm_Mode=$_GET['prm_Mode']:returnError("Error");
  (isset($_GET['prm_Pos']) && !empty($_GET['prm_Pos'])) ? $prm_Pos=$_GET['prm_Pos']:returnError("Error");
  (isset($_GET['prm_QUAL']) && !empty($_GET['prm_QUAL'])) ? $prm_QUAL=$_GET['prm_QUAL']:returnError("Error");
  (isset($_GET['prm_DP']) && !empty($_GET['prm_DP'])) ? $prm_DP=$_GET['prm_DP']:returnError("Error");
  (isset($_GET['prm_DP4']) && !empty($_GET['prm_DP4'])) ? $prm_DP4=$_GET['prm_DP4']:returnError("Error");
  (isset($_GET['prm_Acc']) && !empty($_GET['prm_Acc'])) ? $prm_Acc=$_GET['prm_Acc'] : returnError("Error");

  list($zoom_v,$zoom_r,$zoom_chr)=_cvtZoom($prm_Zoom, $prm_Chr);

  $sQry="";
  if ( $prm_Mode == "dp+s" || $prm_Mode == "s" ) {
    $sQry=" and variant='s'";
  } else if ( $prm_Mode == "dp+i" || $prm_Mode == "i" ) {
    $sQry=" and variant != 's' ";
  } else if ( $prm_Mode == "dp" ) {
    $sQry=" and variant = 'dp' ";
  }

  ////////////////////////////////////////////////// Range
  $e=$zoom_v*$zoom_r*$prm_Pos;
  $s=$e-$zoom_v*$zoom_r;

  ////////////////////////////////////////////////// SQL
  $datas = array();
  $query = "SELECT pos,variant,REF,ALT,EFF,GT,QUAL FROM "
          .$prm_Acc."_variant WHERE chr='".$prm_Chr."' and pos>".$s." and pos<=".$e." and QUAL>=".$prm_QUAL.
          " and DP>=".$prm_DP." and (DP3+DP4)>=".$prm_DP4.$sQry;
  $result = mysql_query($query);
  while ($row = mysql_fetch_row($result, MYSQL_NUM)) {
    if ( $row[1] == "s" ) $varType="SNP";
    if ( $row[1] == "i" ) $varType="INS";
    if ( $row[1] == "d" ) $varType="DEL";
    $datas[]="{\"pos\":\"".$row[0]."\",\"variant\":\"".$varType."\",\"ref\":\"".$row[2]."\",".
              "\"alt\":\"".$row[3]."\",\"eff\":\"".$row[4]."\",\"gt\":\"".$row[5]."\",\"qual\":\"".$row[6]."\"}";
  }

  ////////////////////////////////////////////////// Return
  $rtnString="[";
  for ($i=0; $i<count($datas); $i++) {
    $rtnString=$rtnString.$datas[$i];
    if ( $i<count($datas)-1 ) $rtnString=$rtnString.",";
  }
  $rtnString=$rtnString."]";
  echo $rtnString;

  ////////////////////////////////////////////////// Exit
  exit;


  function returnError($str){
    echo $str;
  }

  function _cvtZoom($str1, $str2) {
    preg_match("/^[0-9]+/", $str1, $r1);
    preg_match('/[b,k]$/', $str1, $r2);
    $v=$r1[0];
    if($r2[0] == "b"){
      $r=1;
      $c=$str2."_b";
    } else {
       $r=1000;
      $c=$str2."_k";
    }
    return array((int)$v,(int)$r, $c);
  }

?>
