<?php
/*
* common.php
* http://tasuke.dna.affrc.go.jp/
*
* Author: Ryutaro Itoh
*
* Copyright (c) 2013 National Institute of Agrobiological Sciences
*
*/
  function _pregMatch($cmd) {
//          if(preg_match("/\;|\||\&|\`|\(|\)|\<|\>|\*|\?|\{|\}|\[|\]|\!/",$cmd)) {
          if(preg_match("/[\;\|\&\`\(\)\<\>\*\?\{\}\[\]\!\r\n]/", $cmd)) {
                  $errmsg = "Input Parameter Invalid!";
                  echo $errmsg;
                  exit;
          }
  }
  function _pregMatchQueryList($list) {
	// "/[\(\)\:]/" are allowed.
//	if(preg_match("/\;|\||\&|\`|\<|\>|\*|\?|\{|\}|\[|\]|\!\"\'/", $list)) {
	if(preg_match("/[\;\|\&\`\<\>\*\?\{\}\[\]\!\"\'\r\n]/", $list)) {
		echo "Input Parameter Invalid!";
		exit;
	}
  }
  function _checkZoom($cmd) {
          if(preg_match("/[0-9].*[kb]/",$cmd)) {
                  $errmsg = "Error: Input Parameter Invalid!";
                  echo $errmsg;
                  exit;
          }
  }
/*
  function _stopError($str){
    echo $str;
    exit;
  }
*/
  function _validate_num($num){
    if (preg_match("/^\d+$/i", $num)) {
       return true;
    }else{
       return false;
    }
  }
  function _isTransposon($str) {
    if(preg_match("/^</", $str)) {
      return True;
    } else {
      return False;
    }
  }
  function _isGtZero($gt) {
    if($gt === "0/0" || $gt === "0|0") {
      return True;
    } else {
      return False;
    }
  }
  function _setSnpEffImpactFilterMap(&$map, $array) {
    // -1:NONE
    // 0: MODIFIER
    // 1: LOW
    // 2: MODERATE
    // 3: HIGH
//    $map = array("0" => True, "1" => True, "2" => True, "3" => True, "-1" => True);

    $keys = array_keys($map);
    foreach($keys as $key) { $map[$key] = False; }
    foreach($array as $impct) { $map[(string)$impct] = True; }

    $allTrue = True;
    foreach($keys as $key) { $allTrue = $allTrue && $map[$key]; }

    $doFilter = False;
    if(!$allTrue) $doFilter = True;	// If all are true, do not filter.
    return $doFilter;
  }
  function _parseSnpEffs($str) {
    $eff_list = explode(",", $str);
    $t=count($eff_list);
    $resarray = array();
    for($i=0; $i<$t; $i++){
	$resarray[] = _parseSnpEff($eff_list[$i]);
    }
    return $resarray;
  }
  function _parseSnpEff($str) {
    $EFFMAP = array('MODIFIER' => 0, 'LOW' => 1, 'MODERATE' => 2, 'HIGH' => 3);
    if(!empty($str)) {
                        $effname = ""; $alt = ""; $geneid = ""; $genename = ""; $impact = ""; $impactc = null;
                        if(preg_match("/^([^\|\(]+)\((.+)$/", $str, $matches)) {
                                // EFF
                                $effname = strtolower($matches[1]);
                                $EffInfo = explode("|", $matches[2]);
                                if(count($EffInfo) > 10) {
                                        // new EFF
                                        $geneid = $EffInfo[5];
                                        $genename = $EffInfo[8];
                                } else {
                                        // old EFF
                                        $geneid = $EffInfo[4];
                                        $genename = $EffInfo[7];
                                }
                                $alt = str_replace(")", "", array_pop($EffInfo));
                                $impact = $EffInfo[0];
                        } else {
                                // ANN
                                $effect = explode("|", $str);
                                $effname = strtolower($effect[1]);
                                $geneid = $effect[3];
                                $genename = $effect[6];
                                $alt = $effect[0];
                                $impact = $effect[2];
                        }
                        $impactc = $EFFMAP[$impact];
    }
    return array("id" => $geneid, "name" => $genename, "alt" => $alt, "eff" => $effname, "impact" => $impact, "impactc" => $impactc);
  }
  function precisionNumDigit($num, $prec) {
        if($num == 0) return "0";       // exactly, "$num===0.0"

        $convNumStr = "";
        if($num > 1) {
                $convNumStr = sprintf("%.". ($prec - 1). "f", $num);
        } else {
                $numStr = sprintf("%.15f", $num);
                $numLen = strlen($numStr);
                $essDisitStart = false;
                $essDigitCount = 0;
                $convNumStr = "";
                for($i=0; $i<$numLen; $i++) {
                        $digitStr = $numStr[$i];
                        if(!$essDisitStart && $digitStr !== "0" && $digitStr !== ".") $essDisitStart = true;
                        $convNumStr .= $digitStr;
                        if($essDisitStart) {
                                $essDigitCount++;
                                if($essDigitCount >= $prec) break;
                        }
                }
        }
        return preg_replace('/0+$/', '', $convNumStr);
   }
   function reverseNucStr($seqStr) {
	$seqArray = str_split($seqStr);
	$revArray = reverseNucArray($seqArray);
	return implode('', $revArray);
   }
   function reverseNucArray($seqArray){
	$len = count($seqArray);
	$revArray = array();
	for($i=$len-1; $i>=0; $i--){
		$base = $seqArray[$i];
		$isLower = ctype_lower($base);
		$revBase = "";
		switch(strtoupper($base)){
			case "A": $revBase="T"; break;
			case "G": $revBase="C"; break;
			case "C": $revBase="G"; break;
			case "T": $revBase="A"; break;
			case "U": $revBase="A"; break;
			case "M": $revBase="K"; break;
			case "K": $revBase="M"; break;
			case "R": $revBase="Y"; break;
			case "Y": $revBase="R"; break;
//			case "W": $revBase="W"; break;
//			case "S": $revBase="S"; break;
			case "H": $revBase="D"; break;
			case "B": $revBase="V"; break;
			case "D": $revBase="H"; break;
			case "V": $revBase="B"; break;
//			case "N": $revBase="N"; break;
			default: $revBase=$seqArray[$i]; break;
		}
		if($isLower) $revBase = strtolower($revBase);
		$revArray[] = $revBase;
	}
	return $revArray;
   }

   $BASE2IUPAC_MAP = array(
	"A" => "A", "T" => "T", "G" => "G", "C" => "C",
	"AT" => "W", "AG" => "R", "AC" => "M", "GT" => "K", "CT" => "Y", "CG" => "S",
	"ACT" => "H", "CGT" => "B", "ACG" => "V", "AGT" => "D",
	"ATGC" => "N"
   );   
   function convBases2Iupac($basesStr) {
/*
	$iupac = "";
	switch(strtoupper($basesStr)){
		case "AT": $iupac = "W"; break;
		case "AG": $iupac = "R"; break;
		case "AC": $iupac = "M"; break;
		case "GT": $iupac = "K"; break;
		case "CT": $iupac = "Y"; break;
		case "CG": $iupac = "S"; break;
		case "A": $iupac = "A"; break;
		case "T": $iupac = "T"; break;
		case "G": $iupac = "G"; break;
		case "C": $iupac = "C"; break;
		case "ACT": $iupac = "H"; break;
		case "CGT": $iupac = "B"; break;
		case "ACG": $iupac = "V"; break;
		case "AGT": $iupac = "D"; break;
		default: $iupac = "N"; break;
	}
//error_log($basesStr. " => ". $iupac);
	return $iupac;
*/
	global $BASE2IUPAC_MAP;
	$basesStr = strtoupper($basesStr);
	if(array_key_exists($basesStr, $BASE2IUPAC_MAP)) {
		return $BASE2IUPAC_MAP[$basesStr];
	} else {
		return "N";
	}
   }
   function convBases2IupacFromArr($basesArr) {
	$len = count($basesArr);
	$basesArrSorted = array();
	for($i=0; $i<$len; $i++) {
		$basesArrSorted[$i] = $basesArr[$i];
	}
        sort($basesArrSorted);
	return convBases2Iupac(implode("", $basesArrSorted));
   }
   function detectAborted() {
	echo " ";
	if(ob_get_level() > 0) ob_flush();
	flush();
   }
   function cleanDir($path) {
    if(!file_exists($path)){
        return;
    }
 
    if(is_file($path)) {
        unlink($path);
        return;
    }
 
    if($handle = opendir($path)) {
        while(false !== ($item = readdir($handle))) {
            if($item === '.' || $item === '..') {
                continue;
            }
            cleanDir($path . DIRECTORY_SEPARATOR . $item);
        }
        closedir($handle);
        rmdir($path);
    }
   }
?>
