Index: trunk/www/dch/db_explorer.php
===================================================================
--- trunk/www/dch/db_explorer.php	(revision 18883)
+++ trunk/www/dch/db_explorer.php	(revision 18883)
@@ -0,0 +1,1414 @@
+<?php
+
+    include("db.php");
+
+ //   ini_set("display_errors", "On");
+ //   ini_set("mysql.trace_mode", "On");
+
+
+if (isset($_GET['db']))
+    $database = $_GET['db'];
+
+$error_con = "";
+
+$db = new mysqli($host, $user, $pw, $database);
+if ($db->connect_error)
+{
+     header("HTTP/1.0 500 Internal server error");
+     $error_con = $db->connect_error;
+     //die("mysqli_connect: ".$db->connect_errno." ".$db->connect_error);
+}
+
+if (isset($_GET["short"]) && !$db->connect_error)
+{
+   $query  = "SELECT URL from ShortURL.ShortURL WHERE `Key`=(".base62_decode($_GET["short"]).")";
+   if ($result = $db->query($query))
+   {
+	$uri = $_SERVER['REQUEST_URI'];
+	$pos = strpos($uri, '?');
+	$uri = $pos===FALSE ? $uri : substr($uri, 0, $pos);
+
+        $row = $result->fetch_assoc();
+        $result->free();
+
+        $url = $row['URL'];
+
+ 	$tiny = $_SERVER['HTTP_HOST'].$uri.'?'.$url;
+
+	if (isset($_GET["print"]) &&
+            strstr($url, "?print")==FALSE &&
+	    strstr($url, "&print")==FALSE)
+            $tiny .= "&print";
+
+        header('Location: //'.$tiny);
+        die("");
+   }
+}
+
+$hidden = isset($_GET["print"]) ? "*{visibility:hidden;}.print{position:fixed;left:0;top:0;}.print *{visibility:visible;}" : "";
+$begin  = isset($_GET["b"]) ? $_GET["b"] : "";
+$end    = isset($_GET["e"]) ? $_GET["e"] : "";
+$source = isset($_GET["s"]) ? intval($_GET["s"]) : 0;
+$group  = isset($_GET["g"]) ? intval($_GET["g"]) : 1;
+$table  = isset($_GET["t"]) ? $_GET["t"] : "LP";
+$cut    = isset($_GET["cut"]) ? trim($_GET["cut"]) : "";
+$having = isset($_GET["hav"]) ? trim($_GET["hav"]) : "";
+$vmin   = isset($_GET["min"]) ? "minValue:".intval($_GET["min"])."," : "";
+$vmax   = isset($_GET["max"]) ? "maxValue:".intval($_GET["max"])."," : "";
+$width  = isset($_GET["w"]) ? floatval($_GET["w"]) : 1;
+$sql_x  = isset($_GET["x"]) ? trim($_GET["x"]) : "";
+$sql_y  = isset($_GET["y"]) ? trim($_GET["y"]) : "";
+$sql_err= isset($_GET["err"]) ? trim($_GET["err"]) : "";
+$rate   = isset($_GET["r"]) ? intval($_GET["r"]) : 6;
+$offset = isset($_GET["o"]) ? floatval($_GET["o"]) : 0;
+$nohist = isset($_GET["no-hist"]) ? 1 : 0;
+$noerr  = isset($_GET["no-errors"]) ? 1 : 0;
+$ontime = isset($_GET["on"]) ? floatval($_GET["on"]) : -1;
+//$clean  = isset($_GET["clean"]) ? "AND fEffectiveOn>0.015" : "";
+
+if (!empty($sql_x))
+    $group = 42;
+
+if ($width<=0)
+   $width = 1;
+
+if (empty($offset))
+   $offset = 0;
+
+/*
+$join   = isset($_GET["join"]) ? "LEFT JOIN ".$_GET["join"]." USING(fNight,fRunID)" : "";
+
+if (isset($_GET["x"]))
+   $group = 42;
+
+if (isset($_GET["y"]))
+   $rate = 44;
+
+// Backward compatibility
+if (isset($_GET["avg"]))
+{
+   $y = $_GET["avg"];
+   $rate = 42;
+}
+
+if (isset($_GET["sum"]))
+{
+   $y = $_GET["sum"];
+   $rate = 43;
+}
+
+if (isset($_GET["hist"]))
+{
+   $x = $_GET["hist"];
+   $rate = 45;
+   $group = 42;
+}
+
+*/
+
+$good = "";
+if (isset($_GET["good"]))
+{
+    $g = $_GET["good"];
+
+    if ($g&0x1) $good .= " AND fNumThreshold750/(cos(fZenithDistanceMean*PI()/180)+0.179*pow(sin(1.89*fZenithDistanceMean*PI()/180),5))/TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))/fEffectiveOn>3.7 ";
+    if ($g&0x2) $good .= " AND ((fNumEvtsAfterCleaning*1.0-fNum27Sec*1.0)/((-2381.1+2766.3*LOG10(fThresholdMinSet)-1049.9*POW(LOG10(fThresholdMinSet),2)+131.05*POW(LOG10(fThresholdMinSet),3))/21.15)/(COS(fZenithDistanceMean*PI()/180)+0.179*POW(SIN(1.89*fZenithDistanceMean*PI()/180),5)))/(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)>16.2 ";
+    if ($g&0x4) $good .= " AND (fNumEvtsAfterQualCuts/(cos(fZenithDistanceMean*PI()/180)+0.179*pow(sin(1.89*fZenithDistanceMean*PI()/180),5))/((8598.9- 13181*log10(fThresholdMinSet)+7567.4*pow(log10(fThresholdMinSet),2)-1925.2*pow(log10(fThresholdMinSet),3)+183*pow(log10(fThresholdMinSet),4))/9.2 ))/(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)>6.7 ";
+    if ($g&0x8) $good .= " AND (fNumEvtsAfterBgCuts/(1.41*POW(fZenithDistanceMean*PI()/180,2)+0.975)/(-7.53e-12*POW(10, LOG10(fThresholdMinSet)*3.69)+1.035) )/(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)>0.6 ";
+}
+
+$sqlbegin  = !empty($begin) ? "AND (DATE(fNight)>='".$begin."')" : "";
+$sqlend    = !empty($end)   ? "AND (DATE(fNight)<='".$end."')" : "";
+$sqlcut    = !empty($cut)   ? "AND (".$cut.") " : "";
+$sqlhaving = !empty($having)? "AND (".$having.") " : "";
+
+// --------------------------------------------------------------------
+
+$query2 = <<<EOT
+
+SELECT
+   COLUMN_NAME
+FROM
+   INFORMATION_SCHEMA.COLUMNS
+WHERE
+   TABLE_SCHEMA='$database' AND
+   TABLE_NAME in ('RunInfo','AnalysisResultsRun$table')
+GROUP BY
+   COLUMN_NAME
+ORDER BY
+   COLUMN_NAME
+
+EOT;
+
+$error2 = "";
+$columns = "";
+
+$result2 = $db->connect_error ? FALSE : $db->query($query2);
+if ($result2)
+{
+    while ($row = $result2->fetch_assoc())
+        $columns .= '"'.$row['COLUMN_NAME'].'",'."\n";
+    $result2->free();
+}
+else
+{
+    $error2 .= $db->error;
+}
+
+// --------------------------------------------------------------------
+
+$query1 = <<<EOT
+
+SELECT
+   fSourceKEY AS k,
+   fSourceName AS name,
+   fRightAscension AS ra
+FROM Source
+WHERE fSourceTypeKey=1
+ORDER BY k
+
+EOT;
+
+$error1 = "";
+
+$sources = array();
+$sourceoptions = "";
+
+$result1 = $db->connect_error ? FALSE : $db->query($query1);
+if ($result1)
+{
+    while ($row = $result1->fetch_assoc())
+    {
+        $sources[$row['k']] = $row;
+        $sourceoptions .= "<option value='".$row['k']."'>".$row['name']."</option>\n";
+    }
+    $result1->free();
+}
+else
+{
+    $error1 .= $db->error;
+}
+
+$sourcename = $source==0 ? "All" : $sources[$source]['name'];
+$ra         = $source==0 ? 0     : $sources[$source]['ra'];
+$sqlsource  = $source==0 ? ""    : "AND fSourceKey=".$source;
+
+// --------------------------------------------------------------------
+
+$unitx = "";
+
+switch ($group)
+{
+case 1:
+    $selectx="fPeriod";
+    $titlex="Period";
+    $axistype="number";
+    $mintime=60;
+    break;
+case 2:
+    //$selectx="FROM_UNIXTIME(UNIX_TIMESTAMP(fRunStart)+(UNIX_TIMESTAMP(fRunStop)-UNIX_TIMESTAMP(fRunStart))/2)";
+    $selectx="STR_TO_DATE(fNight, '%Y%m%d')";
+    $titlex="Night";
+    $axistype="date";
+    $mintime=20;
+    break;
+case 3:
+    $selectx="YEAR(fNight)";//"SUBSTR(fNight,1,4)";
+    $titlex="Year";
+    $axistype="date";
+    $mintime=60;
+    break;
+case 4:
+    $selectx="ADDDATE(DATE(CONCAT(YEAR(ADDDATE(DATE(fNight), INTERVAL - (".$ra."/24.*365+80) DAY)), '-01-01')), INTERVAL + (".$ra."/24.*365+80+365/2) DAY)"; // FIXME shift back to get the center!
+    //$selectx="ADDDATE(DATE(YEAR(ADDDATE(DATE(fNight), INTERVAL - (".$ra."/24.*365+80) DAY))), INTERVAL + (".$ra."/24.*365+80) DAY)";
+    $titlex="Season";
+    $axistype="date";
+    $mintime=60;
+    break;
+case 5:
+    $selectx="FROM_UNIXTIME((UNIX_TIMESTAMP(fRunStop)+UNIX_TIMESTAMP(fRunStart))/2)";
+    $titlex="Time";
+    $axistype="date";
+    $mintime=0.5;
+    break;
+case 6:
+    $bin = isset($width) ? $width : 5;
+    $selectx="FLOOR(fZenithDistanceMean/".$bin.")*".$bin."+".$bin."/2";
+    $titlex="Zd [deg]";
+    $axistype="number";
+    $mintime=0.5;
+    break;
+case 7:
+    $bin = isset($width) ? $width : 50;
+    $selectx="FLOOR(fThresholdMinSet/".$bin.")*".$bin."+".$bin."/2";
+    $titlex="Threshold";
+    $axistype="number";
+    $mintime=0.5;
+    break;
+case 8:
+    $bin = isset($width) ? $width : 5;
+    $selectx="FLOOR(fCurrentsMedMean/".$bin.")*".$bin."+".$bin."/2";
+    $titlex="Current [\u00B5A/pix]";  // \u00B5 = &micro;
+    $axistype="number";
+    $mintime=0.5;
+    break;
+case 9:
+    $selectx="MONTH(fNight)";//"SUBSTR(fNight,1,4)";
+    $titlex="Month";
+    $axistype="date";
+    $mintime=60;
+    break;
+case 42:
+    $bin = isset($width) ? $width : 1;
+    $selectx="FLOOR(((".$sql_x.")-".$offset.")/".$bin.")*".$bin."+".$bin."/2+".$offset;
+    $titlex=addslashes($sql_x)." / ".$bin;
+    $axistype="number";
+    $mintime=0.5;
+    break;
+
+default:
+    $selectx="fPeriod";
+    $titlex="Period";
+    $axistype="number";
+    $mintime=60;
+    break;
+}
+
+if ($ontime>=0)
+   $mintime = $ontime;
+
+// --------------------------------------------------------------------
+
+$isnull = "";
+$unity = "[Hz]";
+$selecterr="1";
+
+$vminval = 0;
+$errors = 0;
+$histogram = 0;
+
+switch ($rate)
+{
+case 1:
+    $selecty="AVG(fTriggerRateMedian)";
+    $isnull="AND NOT ISNULL(fTriggerRateMedian)";
+    $titley="Average TriggerRate";
+    break;
+case 21:
+    $selecty="SUM(fNumPhysicsTrigger)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumPhysicsTrigger)";
+    $titley="PhysicsTriggerRate";
+    break;
+case 22:
+    //$selecty="(SUM(fNumPhysicsTrigger)-SUM(fNum27Sec))/SUM(fOnTime)";
+    $selecty="SUM(fNumPhysicsTrigger*1.0-fNum27Sec*1.0)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumPhysicsTrigger) AND NOT ISNULL(fNum27Sec)";
+    $titley="PhysicsTrigger-27Sec";
+    break;
+case 2:
+    $selecty="SUM(fNumEvtsAfterCleaning)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumEvtsAfterCleaning)";
+    $titley="Rate after Cleaning";
+    break;
+case 23:
+    $selecty="SUM(fNumEvtsAfterCleaning*1.0-fNum27Sec*1.0)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumEvtsAfterCleaning) AND NOT ISNULL(fNum27Sec)";
+    $titley="Rate after Cleaning-27Sec";
+    break;
+case 20:
+    //$selecty="SUM((fNumEvtsAfterCleaning*1.0-fNum27Sec*1.0)/(1-(22.3-6)/22.5/0.4*(LOG10(fThresholdMinSet)-2.5))/(cos(fZenithDistanceMean*PI()/180)+0.18*pow(sin(2*fZenithDistanceMean*PI()/180),3)))/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $selecty="SUM((fNumEvtsAfterCleaning*1.0-fNum27Sec*1.0)/((-2381.1+2766.3*LOG10(fThresholdMinSet)-1049.9*POW(LOG10(fThresholdMinSet),2)+131.05*POW(LOG10(fThresholdMinSet),3))/21.15)/(COS(fZenithDistanceMean*PI()/180)+0.179*POW(SIN(1.89*fZenithDistanceMean*PI()/180),5)))/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumEvtsAfterCleaning) AND LOG10(fThresholdMinSet)<2.8 AND NOT ISNULL(fZenithDistanceMean) AND fThresholdMinSet>0 ";
+    $titley="Rate after cleaning (Zd/TH/27s corrected)";
+    break;
+case 3:
+    $selecty="SUM(fNumEvtsAfterQualCuts)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumEvtsAfterQualCuts)";
+    $titley="Rate after Quality Cuts";
+    break;
+case 4:
+    $selecty="SUM(fNumEvtsAfterBgCuts)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumEvtsAfterBgCuts)";
+    $titley="Rate after Background Cuts";
+    break;
+case 24:
+    $selecty="SUM(fNumEvtsAfterBgCuts/(1.41*POW(fZenithDistanceMean*PI()/180,2)+0.975)/(-7.53e-12*POW(10, LOG10(fThresholdMinSet)*3.69)+1.035) )/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumEvtsAfterBgCuts) AND NOT ISNULL(fZenithDistanceMean) AND NOT ISNULL(fThresholdMinSet)";
+    $titley="BgRate (corrected)";
+    break;
+case 28:
+    $selecty="SUM(fNumExcEvts/((1.41*POW(fZenithDistanceMean*PI()/180,2)+0.975)/(-7.53e-12*POW(10, LOG10(fThresholdMinSet)*3.69)+1.035) ))/SUM(fNumExcEvts)";
+    $isnull="AND NOT ISNULL(fNumExcEvts) AND NOT ISNULL(fZenithDistanceMean) AND NOT ISNULL(fThresholdMinSet)";
+    $titley="Ratio Corrected(fNumEvtsAfterBgCuts) Exc / Exc";
+    break;
+case 25:
+    $selecty="SUM(fNumEvtsAfterQualCuts/(cos(fZenithDistanceMean*PI()/180)+0.179*pow(sin(1.89*fZenithDistanceMean*PI()/180),5))/((8598.9- 13181*log10(fThresholdMinSet)+7567.4*pow(log10(fThresholdMinSet),2)-1925.2*pow(log10(fThresholdMinSet),3)+183*pow(log10(fThresholdMinSet),4))/9.2 ))/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumEvtsAfterQualCuts) AND NOT ISNULL(fZenithDistanceMean) AND NOT ISNULL(fThresholdMinSet)";
+    $titley="QualCutRate (corrected)";
+    break;
+case 29:
+    $selecty="SUM(fNumExcEvts/(cos(fZenithDistanceMean*PI()/180)+0.179*pow(sin(1.89*fZenithDistanceMean*PI()/180),5))/((8598.9- 13181*log10(fThresholdMinSet)+7567.4*pow(log10(fThresholdMinSet),2)-1925.2*pow(log10(fThresholdMinSet),3)+183*pow(log10(fThresholdMinSet),4))/9.2 ))/SUM(fNumExcEvts)";
+    $isnull="AND NOT ISNULL(fNumEvtsAfterQualCuts) AND NOT ISNULL(fZenithDistanceMean) AND NOT ISNULL(fThresholdMinSet)";
+    $titley="Ratio Corrected(fNumEvtsAfterQualCuts) Exc / Exc";
+    break;
+case 30:
+    $selecty="SUM(fNumExcEvts/(pow(cos(fZenithDistanceMean*PI()/180),3)+14.8/21.9*pow(sin(2*fZenithDistanceMean*PI()/180),5))/(1-0.00124/1.21*(fThresholdMinSet-500)*(fThresholdMinSet>=500)))/SUM(fNumExcEvts)";
+    $isnull="AND NOT ISNULL(fNumEvtsAfterQualCuts) AND NOT ISNULL(fZenithDistanceMean) AND NOT ISNULL(fThresholdMinSet)";
+    $titley="Ratio Corrected(fNumExcEvts) Exc / Exc";
+    break;
+case 17:
+    $selecty="SUM(fNumSigEvts)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumSigEvts)";
+    $titley="Signal events";
+    break;
+case 5:
+    $selecty="SUM(fNumBgEvts)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumBgEvts)";
+    $titley="Background events";
+    break;
+case 6:
+    $selecty="SUM(fNumExcEvts)*3600/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $selecterr="EXCERR(SUM(fNumSigEvts), SUM(fNumBgEvts))/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)*3600";
+    $isnull="AND NOT ISNULL(fNumExcEvts)";
+    $titley="Excess events";
+    $unity="[1/h]";
+    $errors = $noerr ? 0 : 1;
+    break;
+case 7:
+    $selecty="SUM(fNum27Sec)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNum27Sec)";
+    $titley="27sec Rate";
+    break;
+case 8:
+    $selecty="SUM(fNumThreshold500)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumThreshold500)";
+    $titley="Threshold 500 Rate";
+    break;
+case 9:
+    $selecty="SUM(fNumThreshold750)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumThreshold750)";
+    $titley="Threshold 750 Rate";
+    break;
+case 10:
+    $selecty="SUM(fNumThreshold1000)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumThreshold1000)";
+    $titley="Threshold 1000 Rate";
+    break;
+case 11:
+    $selecty="SUM(fNumThreshold1250)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumThreshold1250)";
+    $titley="Threshold 1250 Rate";
+    break;
+case 12:
+    $selecty="SUM(fNumThreshold2500)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumThreshold2500)";
+    $titley="Threshold 2500 Rate";
+    break;
+case 13:
+    $selecty="SUM(fNumThreshold5000)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumThreshold5000)";
+    $titley="Threshold 5000 Rate";
+    break;
+case 14:
+    $selecty="SUM(fNumThreshold10000)/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fNumThreshold10000)";
+    $titley="Threshold 10000 Rate";
+    break;
+case 15:
+    $selecty="AVG(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn-fOnTime)";
+    $isnull="AND NOT ISNULL(fOnTime) AND NOT ISNULL(fRunStop) AND NOT ISNULL(fRunStart) AND NOT fRunStop='0000-00-00 00:00:00' AND NOT fRunStart='0000-00-00 00:00:00'";
+    $titley="Ontime difference";
+    $sqlhaving.="AND y>0";
+    $unity="[s]";
+    break;
+case 26:
+    $selecty="AVG(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn-fOnTimeAfterCuts)";
+    $isnull="AND NOT ISNULL(fOnTime) AND NOT ISNULL(fOnTimeAfterCuts) AND NOT ISNULL(fRunStop) AND NOT ISNULL(fRunStart) AND NOT fRunStop='0000-00-00 00:00:00' AND NOT fRunStart='0000-00-00 00:00:00'";
+    $titley="Calculated ontime minus ontime after cuts";
+    $unity="[s]";
+    break;
+case 27:
+    $selecty="AVG(fOnTime-fOnTimeAfterCuts)";
+    $isnull="AND NOT ISNULL(fOnTime) AND NOT ISNULL(fOnTimeAfterCuts) AND NOT ISNULL(fRunStop) AND NOT ISNULL(fRunStart) AND NOT fRunStop='0000-00-00 00:00:00' AND NOT fRunStart='0000-00-00 00:00:00'";
+    $titley="Average difference between ontime and ontime after cuts";
+    $unity="[s]";
+    break;
+case 18:
+    $selecty="AVG(fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fEffectiveOn)";
+    $titley="Average (On time / elapsed time)";
+    $unity="";
+    $vminval=0.8;
+    break;
+case 19:
+    $selecty="SUM(fOnTime)/SUM(fOnTime/fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fOnTime) AND NOT ISNULL(fEffectiveOn)";
+    $titley="SUM(On time) / SUM(Elapsed time)";
+    $unity="";
+    $vminval=0.8;
+    break;
+case 16:
+    $selecty="SUM(fNumThreshold750/(cos(fZenithDistanceMean*PI()/180)+0.179*pow(sin(1.89*fZenithDistanceMean*PI()/180),5)))/SUM(TIME_TO_SEC(TIMEDIFF(fRunStop,fRunStart))*fEffectiveOn)";
+    $isnull="AND NOT ISNULL(fOnTime) AND NOT ISNULL(fRunStop) AND NOT ISNULL(fRunStart) AND NOT fRunStop='0000-00-00 00:00:00' AND NOT fRunStart='0000-00-00 00:00:00' AND NOT ISNULL(fZenithDistanceMean) AND NOT ISNULL(fNumThreshold750)";
+    $titley="Threshold 750 Rate (Zd corrected)";
+    break;
+case 42:
+    $selecty="AVG(".$sql_y.")";
+    $isnull="AND NOT ISNULL(".$sql_y.")";
+    $titley="Average ".$sql_y;
+    $unity="";
+    //$vmin ="";
+    $histogram = 1;//$nohist ? 0 : 1;
+    break;
+case 43:
+    $selecty="SUM(".$sql_y.")";
+    $isnull="AND NOT ISNULL(".$sql_y.")";
+    $titley="Sum of ".$sql_y;
+    $unity="";
+    //$vmin ="";
+    $histogram = 1;//$nohist ? 0 : 1;
+    break;
+case 44:
+    $selecty=$sql_y;
+    $titley=$sql_y;
+    $unity="";
+    //$vmin ="";
+    $histogram = 1;//$nohist ? 0 : 1;
+    break;
+case 45:
+    $selecty="COUNT(".(empty($sql_y)?"*":$sql_y).")";
+    $titley="Counts";
+    $unity="";
+    //$vmin ="";
+    $histogram = 1;//$nohist ? 0 : 1;
+    break;
+case 46:
+    $selecty="LOG10(COUNT(".(empty($sql_y)?"*":$sql_y)."))";
+    $titley="log10(Counts)";
+    $unity="";
+    //$vmin ="";
+    $histogram = 1;//$nohist ? 0 : 1;
+    break;
+default:
+    $selecty="AVG(fTriggerRateMedian)";
+    $isnull="AND NOT ISNULL(fNumExcEvts) AND NOT ISNULL(fNumBgEvts) AND NOT ISNULL(fNumSigEvts)";
+    $titley="TriggerRate";
+    break;
+}
+
+// --------------------------------------------------------------------
+/*
+SELECT
+   o.night,
+   MIN(o.start),
+   MAX(o.stop),
+   SUM(o.sigevts),
+   SUM(o.bgevts),
+   ROUND(SUM(o.ot)/60.,1)
+FROM
+(
+   SELECT
+      fNight,
+      fRunID,
+      fOnTimeAfterCuts AS ot,
+      fRunStart AS start,
+      fRunStop AS stop,
+      fNumSigEvts AS sigevts,
+      fNumBgEvts AS bgevts,
+      if (
+          @night=fNight AND FLOOR((@os+fOnTimeAfterCuts)/20./60.)<1,
+          @bl,
+          @bl := @bl + 1
+         ) as block,
+      if (
+          @night=fNight AND FLOOR((@os+fOnTimeAfterCuts)/20./60.)<1,
+          @os := @os + fOnTimeAfterCuts,
+          @os := fOnTimeAfterCuts
+         ) as os,
+      @os/20./60. AS a,
+      FLOOR(@os/20./60.) AS b,
+      @night := fNight AS night
+   FROM RunInfo
+   LEFT JOIN AnalysisResultsRunLP USING(fNight,fRunID)
+   CROSS JOIN
+   (
+      SELECT
+         @night := 0,
+         @os    := 0,
+         @bl    := 0
+   ) PARAMS
+   WHERE
+      fNight BETWEEN 20130414 AND 20130415
+      AND fRunTypeKey=1
+      AND fSourceKey=1
+) o
+
+GROUP BY block
+*/
+
+// --------------------------------------------------------------------
+
+$query0 = <<<EOT
+
+SELECT
+    ($selectx) AS x,
+    ($selecty) AS y,
+    (SUM(fOnTimeAfterCuts)/60) AS ontime,
+    ($selecterr) AS e,
+    (LIMA(SUM(fNumSigEvts), SUM(fNumBgEvts))) AS s,
+    (MIN(fRunStart)) as start,
+    (MAX(fRunStop)) as stop,
+    (MIN(fZenithDistanceMin)) as zdmin,
+    (MAX(fZenithDistanceMax)) as zdmax,
+    (MIN(fAzimuthMin)) as azmin,
+    (MAX(fAzimuthMax)) as azmax,
+    (MIN(fThresholdMinSet)) as thmin,
+    (MAX(fThresholdMInSet)) as thmax
+FROM RunInfo
+LEFT JOIN AnalysisResultsRun$table USING(fNight,fRunID)
+WHERE
+    fRunTypeKey=1 $sqlsource
+    $sqlbegin $sqlend
+    $isnull
+    $good
+    $sqlcut
+GROUP BY x
+HAVING
+    (ontime>$mintime)
+    $sqlhaving
+
+EOT;
+/*
+#    SUM(fNumExcEvts)/SUM(fOnTimeAfterCuts)*3600 AS y,
+    AND NOT ISNULL(fNumSigEvts)
+    AND NOT ISNULL(fNumExcEvts)
+    AND NOT ISNULL(fNumBgEvts)
+*/
+
+$var0 = "";
+$error0 = "";
+$data = "<table id='list'>\n <tr><th>X</th><th>Y</th><th>E</th><th>OnTime</th><th>Start</th><th>Stop</th><th>Zdmin</th><th>Zdmax</th><th>Azmin</th><th>Azmax</th><th>THmin</th><th>THmax</th></tr>\n";
+
+$timeStart = microtime(true);
+$result0 = $db->connect_error ? FALSE : $db->query($query0);
+$timeMeasured = number_format((microtime(true)-$timeStart)*1000, 2, ".", "");
+if ($result0)
+{
+    while ($row = $result0->fetch_assoc())
+    {
+        $data .= " <tr><td>".$row['x']."</td><td>".$row['y']."</td><td>".$row['e']."</td><td>".$row['ontime']."</td><td>".$row['start']."</td><td>".$row['stop']."</td><td>".$row['zdmin']."</td><td>".$row['zdmax']."</td><td>".$row['azmin']."</td><td>".$row['azmax']."</td><td>".$row['thmin']."</td><td>".$row['thmax']."</td></tr>\n";
+
+        switch ($group)
+        {
+        case 3: // Year
+            $x     = "new Date('".$row['x']."-07-01')";
+            $xtext = $titlex." ".$row['x'];
+            break;
+        case 9: // Month
+            $x     = "new Date('2000-".$row['x']."-15')";
+            $xtext = $titlex." ".$row['x'];
+            break;
+        case 2: // Night
+        case 4: // Season
+        case 5: // Run
+            $x     = "new Date('".$row['x']."')";
+            $xtext = $titlex." ".$row['x'];
+            break;
+        default:
+            $x     = $row['x'];
+            $xtext = $titlex." ".$row['x']." ".$unitx;
+        }
+
+        $y    = $row['y'];
+        $ymin = $row['y']-$row['e'];
+        $ymax = $row['y']+$row['e'];
+        $s    = round($row['s'], 2);
+        $sr   = round($row['s']/sqrt($row['ontime']/60), 1);
+        $t    = round($row['ontime'], 2);
+	$time = $t>60 ? round($row['ontime']/60,2).' h' : round($row['ontime'],1).' min';
+        $start= $row['start'];
+        $stop = $row['stop'];
+        $zdmin= $row['zdmin'];
+        $zdmax= $row['zdmax'];
+        $azmin= $row['azmin'];
+        $azmax= $row['azmax'];
+        $thmin= $row['thmin'];
+        $thmax= $row['thmax'];
+
+        // <entry>
+        $var0 .= "[";
+        $var0 .= $x.",";
+        $var0 .= $y.",";
+
+        if ($histogram==1 && !$nohist)
+            $var0 .= $y.",0,0,";
+
+        if ($errors==1)
+        {
+            $var0 .= $y.",";
+            $var0 .= $ymin.",";
+            $var0 .= $ymax.",";
+        }
+
+        // <tooltip>
+        $var0 .= "'<p>".addslashes($xtext);
+
+	if ($errors==1)
+        {
+            $var0 .= "<p>".round($y,1)." &plusmn ".round($row['e'],1);
+ 	    $var0 .= "<p>".$s." &sigma;";
+            $var0 .= "<p>".$sr." &sigma;/&radic;h";
+        }
+        else
+            $var0 .= "<p>".round($y,3);
+
+        $var0 .= "<p>".$time;
+        $var0 .= "<p>".$start." &ndash; ".$stop;
+        $var0 .= "<p>Zd=[".$zdmin.";".$zdmax."] Az=[".$azmin.";".$azmax."]";
+        $var0 .= "<p>TH=[".$thmin.";".$thmax."]";
+        $var0 .= "'";
+        // </tooltip>
+
+        $var0 .= "],\n";
+        // </entry>
+   }
+
+    $result0->free();
+}
+else
+{
+    $error0 .= $db->error;
+}
+
+// --------------------------------------------------------------------
+
+if (!isset($_GET['list']) && !isset($_GET['list-only']))
+   $data="";
+else
+   $data.="</table>\n<hr>\n";
+
+$querycol0 = colorize($query0);
+$querycol1 = colorize($query1);
+$errorcol_con = !empty($error_con) ? colorize($error_con) : "";
+$errorcol2    = !empty($error2)    ? colorize($error2)   ."\n\n".$querycol2 : "";
+$errorcol1    = !empty($error1)    ? colorize($error1)   ."\n\n".$querycol1 : "";
+$errorcol0    = !empty($error0)    ? colorize($error0)   ."\n\n".$querycol0 : "";
+$has_error = empty($error_con) && empty($error0) && empty($error1) && empty($error2) ? 0 : 1;
+
+$intervalStyle = $histogram==1 && !$nohist ? 'boxes' : 'bars';
+$pointSize     = $histogram==1 && !$nohist ? 'pointSize:0,' : '';
+$boxWidth      = $histogram==1 && !$nohist ? 1.6 : 0;
+
+// boxWidth: Could be used as x error bar for equidistant points
+
+
+$uri = $_SERVER['REQUEST_URI'];
+$pos = strpos($uri, '?');
+$arg = $pos===FALSE ? ""   : substr($uri, $pos+1);
+$uri = $pos===FALSE ? $uri : substr($uri, 0, $pos);
+$min = isset($_GET["min"]) ? intval($_GET["min"]) : "";
+$max = isset($_GET["max"]) ? intval($_GET["max"]) : "";
+$listonly = isset($_GET["list-only"]) ? 1 : 0;
+
+$hiddenBeg = isset($_GET['bx']) ? $_GET['bx'] : "";
+$hiddenEnd = isset($_GET['ex']) ? $_GET['ex'] : "";
+
+$hiddenInput ="";
+if (isset($_GET["t"]))
+  $hiddenInput .= "<input type='hidden' name='t' value='".$_GET["t"]."'>\n";
+if (isset($_GET["db"]))
+  $hiddenInput .= "<input type='hidden' name='db' value='".$_GET["db"]."'>\n";
+if (isset($_GET["good"]))
+  $hiddenInput .= "<input type='hidden' name='good' value='".$_GET["good"]."'>\n";
+
+
+// --------------------------------------------------------------------
+/*
+$curl = curl_init();
+curl_setopt($curl, CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$uri);
+curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
+curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);  
+$tinyurl = curl_exec($curl);
+curl_close($curl);  
+*/
+
+// --------------------------------------------------------------------
+
+/*
+[9:51:32 PM] Lamouette: mysql> explain ShortURL;
++----------+------------------+------+-----+-------------------+-----------------------------+
+| Field    | Type             | Null | Key | Default           | Extra                       |
++----------+------------------+------+-----+-------------------+-----------------------------+
+| Key      | int(10) unsigned | NO   | PRI | NULL              | auto_increment              |
+| URL      | varchar(1024)    | NO   |     | NULL              |                             |
+| UserName | varchar(50)      | NO   |     | NULL              |                             |
+| LastUpd  | timestamp        | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
++----------+------------------+------+-----+-------------------+-----------------------------+
+4 rows in set (0.00 sec)
+*/
+
+/*
+*/
+
+
+$tinyurl = "";
+if ($has_error==0 && strlen($arg)>16 && empty($print) && !$db->connect_error)
+{
+   $query2  = "INSERT INTO ShortURL.ShortURL (URL) VALUES ('".$arg."') ON DUPLICATE KEY UPDATE `Key`=LAST_INSERT_ID(`Key`) ";
+   if ($result2 = $db->query($query2))
+   {
+        $tiny = $_SERVER['HTTP_HOST'].$uri."?short=".base62_encode($db->insert_id);
+        $tinyurl = "<tt style='padding:2px;background:#eef;'>Short URL: <A HREF=//".$tiny.">".$tiny."</A></tt>";
+   }
+}
+
+// --------------------------------------------------------------------
+
+echo <<<EOT
+
+<!DOCTYPE HTML>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Database Explorer</title>
+<script src="https://code.jquery.com/jquery-2.2.1.min.js"        integrity="sha256-gvQgAFzTH6trSrAWoH1iPo9Xc96QxSZ3feW6kem+O00=" crossorigin="anonymous"></script>
+<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js" integrity="sha256-xNjb53/rY+WmG+4L6tTl9m6PpqknWZvRt0rO1SRnJzw=" crossorigin="anonymous"></script>
+
+<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
+
+<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
+<script type="text/javascript">
+    if ($listonly==0)
+    {
+       google.charts.load('current', {packages: ['corechart']});
+       google.charts.setOnLoadCallback(drawAxisTickColors);
+    }
+
+    $(function() {
+
+    $(document).tooltip();
+
+    var availableTags = [
+      "ABS(",
+      "ACOS(",
+      "ADDDATE(",
+      "ADDTIME(",
+      "AND ",
+      "ASIN(",
+      "ATAN(",
+      "ATAN2(",
+      "AVG(",
+      "CEIL(",
+      "CONCAT(",
+      "COS(",
+      "COUNT(",
+      "DATE(",
+      "DAY(",
+      "DEGREES(",
+      "EXCERR(",
+      "EXP(",
+      "FLOOR(",
+      "FROM_UNIXTIME(",
+      "INTERVAL ",
+      "ISNULL(",
+      "LIMA(",
+      "LN(",
+      "LOG(",
+      "LOG10(",
+      "LOG2(",
+      "MAX(",
+      "MIN(",
+      "MINUTE(",
+      "MONTH(",
+      "OR ",
+      "PI()",
+      "POW(",
+      "RADIANS(",
+      "RAND(",
+      "ROUND(",
+      "SIGN(",
+      "SIN(",
+      "SUM(",
+      "SQRT(",
+      "TAN(",
+      "TIME_TO_SEC(",
+      "TIMEDIFF(",
+      "TRUNCATE(",
+      "UNIX_TIMESTAMP(",
+      "YEAR(",
+$columns
+];
+
+    function acSource( request, response )
+    {
+       //var pos = $($(this)).get(0).selectionStart;
+       var pos = this.element[0].selectionStart;
+       var t = request.term.substr(0, pos);
+       var l = t.match(/\w*$/);
+       response( $.ui.autocomplete.filter(availableTags, String(l)));
+    }
+    function acSelect ( event, ui )
+    {
+       // $(this)[0] === this
+       // "this" was $($(this)).get(0)
+       var pos = this.selectionStart;
+       var idx = this.value.substr(0, pos).match(/\w*$/).index;
+       this.value = this.value.substr(0, idx)+ui.item.value+this.value.substr(pos);
+       this.selectionStart = idx+ui.item.value.length;
+       this.selectionEnd   = idx+ui.item.value.length;
+       return false;
+    }
+    function acFocus(event, ui) { event.preventDefault(); return false; }
+
+
+    $( "#input_x" ).autocomplete( {source: acSource, minLength:1, select: acSelect, focus: acFocus });
+    $( "#input_y" ).autocomplete( {source: acSource, minLength:1, select: acSelect, focus: acFocus });
+    $( "#input_err").autocomplete({source: acSource, minLength:1, select: acSelect, focus: acFocus });
+    $( "#sql_cut" ).autocomplete( {source: acSource, minLength:1, select: acSelect, focus: acFocus });
+    $( "#having"  ).autocomplete( {source: acSource, minLength:1, select: acSelect, focus: acFocus });
+
+    $( "#button_submit" ).button();
+    $( "#button_submit" ).button({
+      icons: {
+        primary: "ui-icon-image"
+      },
+      text: true
+    });
+
+    $("#input_x").prop('disabled', $group!=42);
+
+    $( "#select_x" ).selectmenu({
+       change: function( event, data ) {
+          console.log(JSON.stringify(data));
+          $("#input_x").prop('disabled', data.item.value!=42);
+          $("#width").spinner(data.item.value!=42 && data.item.value!=7 && data.item.value!=8 ? "disable" : "enable");
+          $("#offset").spinner(data.item.value!=42 && data.item.value!=7 && data.item.value!=8 ? "disable" : "enable");
+          $("#nohist").prop('disabled', data.item.value<42);
+       }
+     });
+
+    $( "#select_y" ).selectmenu({
+       change: function( event, data ) {
+          console.log(JSON.stringify(data));
+          $("#input_y").prop('disabled', data.item.value<42);
+          $("#input_err").prop('disabled', data.item.value<42);
+          //$("#noerr").prop('disabled', data.item.value<42);
+       }
+    });
+
+    $( "#source" ).selectmenu();
+
+    $("#input_y").prop('disabled', $rate<42);
+    $("#input_err").prop('disabled', $rate<42);
+
+    $('#select_x').val($group).selectmenu("refresh");
+    $('#select_y').val($rate).selectmenu("refresh");
+    $('#source').val($source).selectmenu("refresh");
+    $('#sql_cut').val("$cut");
+    $('#input_x').val("$sql_x");
+    $('#input_y').val("$sql_y");
+    $('#input_err').val("$sql_err");
+    $('#having').val("$having");
+
+    $( "#date_beg" ).datepicker();
+    $( "#date_end" ).datepicker();
+
+    var date_opt =
+    {
+       dateFormat: 'yy-mm-dd',
+       minDate: '2011-10-10',
+       maxDate: '+1',
+       showButtonPanel: true,
+       showOtherMonths: true,
+       selectOtherMonths: true,
+       changeYear: true,
+       autoSize: true,
+       /*inline: true,*/
+    }
+
+    $( "#width" ).val($width);
+    $( "#offset" ).val($offset);
+    $('#min').val($min);
+    $('#max').val($max);
+    $('#ontime').val($mintime);
+
+    $( "#width" ).spinner();
+    $( "#offset" ).spinner();
+    $( '#min' ).spinner();
+    $( '#max' ).spinner();
+    $( '#ontime' ).spinner();
+
+    $("#offset").spinner($group!=42 && $group!=6 && $group!=7 && $group!=8 ? "disable" : "enable");
+    $("#width").spinner( $group!=42 && $group!=6 && $group!=7 && $group!=8 ? "disable" : "enable");
+    $("#width").spinner('option', { min: 0} );
+
+    $('#min').spinner("$min"=="" ? "disable" : "enable");
+    $('#max').spinner("$max"=="" ? "disable" : "enable");
+    $('#ontime').spinner("$ontime"=="-1" ? "disable" : "enable");
+
+    $( "#enable_min" ).prop('checked', "$min"!="");
+    $( "#enable_max" ).prop('checked', "$max"!="");
+    $( "#enable_ontime" ).prop('checked', "$ontime"!="-1");
+
+    if ($has_error)
+    {
+        $( "#shorturl" ).hide();
+        $( "#chart_area" ).hide();
+        $( "#error" ).show();
+    }
+
+    $( "#date_beg" ).datepicker('option', 'disabled', "$begin"=="");
+    $( "#date_end" ).datepicker('option', 'disabled', "$end"=="");
+
+    $( "#date_beg" ).datepicker('option', date_opt);
+    $( "#date_end" ).datepicker('option', date_opt);
+
+    $( "#date_beg" ).datepicker("setDate", "$begin"=="" ? "2011-10-10" : "$begin");
+    $( "#date_end" ).datepicker("setDate", "$end"=="" ? "+1d" : "$end");
+
+    $( "#enable_beg" ).prop('checked', "$begin"!="");
+    $( "#enable_end" ).prop('checked', "$end"!="");
+
+    $( "#date_beg" ).datepicker('option', 'altField', '#hidden_beg');
+    $( "#date_end" ).datepicker('option', 'altField', '#hidden_end');
+
+    $( "#nohist" ).prop('checked', $nohist==1);
+    $( "#noerr" ).prop('checked', $noerr==1);
+
+    $( "#enable_beg" ).change(function(event,data) { $("#date_beg").datepicker('option', 'disabled', !$(this).prop('checked') );  } );
+    $( "#enable_end" ).change(function(event,data) { $("#date_end").datepicker('option', 'disabled', !$(this).prop('checked') );  } );
+    $( "#enable_min" ).change(function(event,data) { $("#min").spinner('option', 'disabled', !$(this).prop('checked') );  } );
+    $( "#enable_max" ).change(function(event,data) { $("#max").spinner('option', 'disabled', !$(this).prop('checked') );  } );
+    $( "#enable_ontime" ).change(function(event,data) { $("#ontime").spinner('option', 'disabled', !$(this).prop('checked') );  } );
+
+    $( "#nohist" ).prop('disabled', !$histogram);
+    //$( "#noerr" ).prop('disabled', $histogram);
+
+    if ($listonly==1)
+        $( "#chart_area" ).hide();
+  });
+
+/*
+alert(
+(new Date("2012-10-10"))+"\\n"+                // 2h  +0200
+(new Date(2012,10-1,10))+"\\n"+                // 0h  +0200
+(new Date("2012-10-10 03:00:00"))+"\\n"+       // 3h  +0200
+(new Date("2012-10-10 03:00:00 UTC"))+"\\n"+   // 5h  +0200
+(new Date("2012-10-10 03:00:00 +0000"))+"\\n"+ // 5h  +0200
+(new Date(2012,10-1,10,3,0,0))                 // 3h  +0200
+);
+*/
+
+    function drawAxisTickColors()
+    {
+      var data = new google.visualization.DataTable();
+      try
+      {
+         data.addColumn('$axistype', 'x');
+         data.addColumn('number', 'excessrate');
+         if ($errors==1 || ($histogram==1 && $nohist==0))
+         {
+            data.addColumn({id:'val', type:'number', role:'interval'});
+            data.addColumn({id:'min', type:'number', role:'interval'});
+            data.addColumn({id:'max', type:'number', role:'interval'});
+         }
+         data.addColumn({id:'tooltip', type:'string', role:'tooltip', p:{html:true}});
+         data.addRows([
+$var0
+]);
+      }
+      catch (e)
+      {
+         $( "#error" ).html(e);
+         $( "#shorturl" ).hide();
+         $( "#chart_area" ).hide();
+         $( "#error" ).show();
+         return;
+      }
+
+      var options = {
+      tooltip: {isHtml: true},
+      lineWidth: 0,
+        title: "$titley vs $titlex [$sourcename]",
+          height: 400,
+          width:'90%',
+        hAxis: {
+            title: '$titlex $unitx',
+            gridlines: {
+              //count: "-1",
+              units: {
+                 months:  { format: [ "MMM" ] },
+                 minutes: { format: [ "HH:mm" ] },
+                 hours:   { format: [ "MM/dd HH:mm" ] }, // MM/dd HH:mm
+                 days:    { format: [ "MM/dd" ] }        // yyyy/MM/dd
+              },
+            },
+            minorGridlines: {
+              units: {
+                 hours: { format: [ "HH" ] },
+                 //days: { format: [ "dd" ] },
+              }
+            },
+        },
+        vAxis: {
+            title: '$titley $unity',
+            $vmin
+            $vmax
+        //chartArea: {left:60,top:40,bottom:40,width:'90%'},
+        },
+        legend: 'none',
+        $pointSize
+        intervals: {
+                // Normal error bars
+ 	        style: '$intervalStyle',
+                barWidth: 0.5,
+                lineWidth: 1,
+                boxWidth: $boxWidth, 
+        },
+        interval: {
+           val: {
+             style: 'boxes',
+             fillOpacity: 0.5,
+             color: '#BBB'
+           },
+         },
+        explorer: {
+            keepInBound:true,
+            actions:['dragToZoom','rightClickToReset'],
+            maxZoomIn: 0.000001,
+        },
+      };
+
+      var chart0 = new google.visualization.ScatterChart(document.getElementById('chart_div'));
+      chart0.draw(data, options);
+      document.getElementById('print_chart').innerHTML = '<a href="' + chart0.getImageURI() + '">Print</a>';
+
+      console.log("Google.chart.ready");
+    }
+</script>
+<style>
+  $hidden
+
+/* Configration of jQuery UI */
+span.ui-selectmenu-text { padding: 0 5px 0 5px !important; }
+.hasDatepicker { padding: 0 5px 0 5px !important; }
+.ui-widget { font-size:16px;}
+span.ui-button-text { padding-top: 3px !important; padding-bottom: 3px !important; }
+//  span.ui-button-text { text-color: black !important; }
+
+/* Configuration for debug table */
+table { color: #333; font-family: Helvetica, Arial, sans-serif; width: 640px; border-collapse: collapse; border-spacing: 0; }
+td, th { border: 2px solid white; transition: all 0.3s; white-space: nowrap; padding: 3px; }
+#list th { background: #DFDFDF; font-weight: bold; }
+#list td { background: #FAFAFA; text-align: center; }
+#list tr:nth-child(even) td { background: #F1F1F1; }
+#list tr:nth-child(odd) td { background: #FEFEFE; }
+#list tr td:hover { background: #666; color: #FFF; }
+
+/* Configuration for tooltip */
+div.google-visualization-tooltip { font-family: Sans; font-size: 12px; }
+div.google-visualization-tooltip p { margin-top: 0px; margin: 0.5ex 1ex 0.5ex 1ex; }
+div.google-visualization-tooltip p:nth-child(1) { color: blue; font-weight: bold; font-style: italic; }
+div.google-visualization-tooltip p:nth-child(2) { font-weight: bold; }
+div.google-visualization-tooltip p:last-child   { font-style: italic; }
+
+</style>
+</head>
+
+<body>
+
+<div class="ui-widget">
+<form action="#">
+
+  <fieldset>
+    <label for="enbale_beg">From</label>
+    <input type="checkbox" id="enable_beg" title="Enable a lower date limit">
+    <input type="text" name="b" id="date_beg">
+    <!--<input type="hidden" name="bx" id="hidden_beg">-->
+
+    <label for="enbale_end">To</label>
+    <input type="checkbox" id="enable_end" title="Enable an upper date limit">
+    <input type="text" name="e" id="date_end">
+    <!--<input type="hidden" name="ex" id="hidden_end">-->
+
+    <label for="width" title="Width of the range in which data is grouped together">Bin width:</label>
+    <input id="width" name="w" style="width:4em">
+
+    <label for="offset" title="Normally binning starts at 0. This allows an artificial shift of the bins.">Bin shift:</label>
+    <input id="offset" name="o" style="width:5em">
+
+    <label for="nohist">Nohist:</label>
+    <input type="checkbox" id="nohist" name ="no-hist" title="Disable display as histogram">
+
+    <label for="noerr">Noerr:</label>
+    <input type="checkbox" id="noerr" name="no-errors" title="Disable error bars">
+
+    <p style="margin-top: 16px">
+
+    <label for="select_x">Select x</label>
+    <select name="g" id="select_x">
+      <optgroup label="User defined">
+         <option value="42">User defined</option>
+      </optgroup>
+      <optgroup label="By time">
+         <option value="5">Run</option>
+         <option value="2">Night</option>
+         <option value="1">Period</option>
+         <option value="4">Season</option>
+         <option value="9">Month</option>
+         <option value="3">Year</option>
+      </optgroup>
+      <optgroup label="Pre defined">
+         <option value="6">Zenith angle</option>
+         <option value="7">Threshold</option>
+         <option value="8">Current</option>
+      </optgroup>
+    </select>
+
+    <label for="select_y">Select y</label>
+    <select name="r" id="select_y">
+      <optgroup label="User defined">
+         <option value="44">User defined</option>
+      </optgroup>
+      <optgroup label="Pre defined">
+         <option value="45">Counts</option>
+         <option value="46">log10(Counts)</option>
+         <option value="43">Sum</option>
+         <option value="42">Average</option>
+      </optgroup>
+      <optgroup label="Analysis event rates [Effective on time]">
+         <option value="5">Background rate</option>
+         <option value="17">Signal rate</option>
+         <option value="6">Excess rate</option>
+      </optgroup>
+      <optgroup label="Raw event rates [Effective on time]">
+         <option value="21">Physics trigger</option>
+         <option value="22">Physics trigger minus 27s events</option>
+         <option value="2">Events after cleaning</option>
+         <option value="23">Events after cleaning minus 27s events</option>
+         <option value="3">Events after quality cuts</option>
+         <option value="4">Events after background cuts</option>
+         <option value="6">Excess events</option>
+      </optgroup>
+
+      <optgroup label="Corrected [Zd/TH] event rates [Eff. on time]">
+         <option value="20">Events after cleaning minus 27s events</option>
+	 <option value="24">Events after background cuts</option>
+	 <option value="25">Events after quality cuts</option>
+         <option value="16">Artifical trigger TH750</option>
+      </optgroup>
+
+      <optgroup label="Artificial trigger rates [Effective on time]">
+         <option value="7">27s events</option>
+         <option value="8">TH500</option>
+         <option value="9">TH750</option>
+         <option value="10">TH1000</option>
+         <option value="11">TH1250</option>
+         <option value="12">TH2500</option>
+         <option value="13">TH5000</option>
+         <option value="14">TH10000</option>
+      </optgroup>
+
+      <optgroup label="On time comparison">
+	 <option value="15">Avg difference Eff. on time minus Stop-Start time</option>
+	 <option value="26">Avg difference Eff. on time minus OnTimeAfterCuts</option>
+	 <option value="27">Avg Stop-Start time minus OnTimeAfterCuts</option>
+	 <option value="18">Avg FTM effective on time</option>
+	 <option value="19">Sum FTM on time divided by Sum FTM elapsed time</option>
+      </optgroup>
+
+      <optgroup label="Others">
+	 <option value="28">Excess rate correction factor (fNumEvtsAfterBgCuts / PRELIMINARY)</option>
+	 <option value="29">Excess rate correction factor (fNumEvtsAfterQualCuts / PRELIMINARY)</option>
+	 <option value="30">Excess rate correction factor (fNumExcEvts / PRELIMINARY)</option>
+      </optgroup>
+    </select>
+
+    <label for="source">Source</label>
+    <select name="s" id="source">
+      <optgroup label="All data">
+        <option value="0">All data</option>
+      </optgroup>
+      <optgroup label="Sources">
+$sourceoptions
+      </optgroup>
+    </select>
+
+  <table style='width:100%'>
+   <tr>
+    <td align="right" width="1%">
+     <label for="input_x">X: </label>
+    </td>
+    <td>
+     <!--<input id="input_x" name="x" style="width:100%">-->
+     <textarea id="input_x" name="x" style="width:100%" rows="1" maxlength="10000" wrap="soft"></textarea>
+    </td>
+   </tr>
+   <tr>
+    <td align="right" width="1%">
+     <label for="input_y">Y: </label>
+    </td>
+    <td>
+     <!--<input id="input_y" name="y" style="width:100%">-->
+     <textarea id="input_y" name="y" style="width:100%" rows="1" maxlength="10000" wrap="soft"></textarea>
+    </td>
+   </tr>
+<!--   <tr>
+    <td align="right" width="1%">
+     <label for="input_err">E: </label>
+    </td>
+    <td>
+     <textarea id="input_err" name="err" style="width:100%" rows="1" maxlength="10000" wrap="soft"></textarea>
+    </td>
+   </tr>
+-->   <tr>
+    <td align="right" width="1%">
+     <label for="sql_cut">Cut: </label>
+    </td>
+    <td>
+     <!--<input id="sql_cut" name="cut" style="width:100%">-->
+     <textarea id="sql_cut" name="cut" style="width:100%" rows="1" maxlength="10000" wrap="soft"></textarea>
+    </td>
+   </tr>
+   <tr>
+    <td align="right" width="1%">
+     <label for="having">Hav: </label>
+    </td>
+    <td>
+     <textarea id="having" name="hav" style="width:100%" rows="1" maxlength="10000" wrap="soft"></textarea>
+    </td>
+   </tr>
+  </table>
+
+  <br>
+
+  <button id="button_submit">Plot!</button>
+  <!--<button id="button_tinyurl">Tiny URL</button>-->
+
+  <label for="min" title="Minimum y-axis value (only if outside of the data range)">Min:</label>
+  <input type="checkbox" id="enable_min">
+  <input id="min" name="min" style="width:4em">
+
+  <label for="max" title="Maximum y-axis value (only if outside of the data range)">Max:</label>
+  <input type="checkbox" id="enable_max">
+  <input id="max" name="max" style="width:4em">
+
+  <label for="ontime" title="To avoid outliers, this can be used to limit the ontime for which a bin is displayed [min]">On-time limit:</label>
+  <input type="checkbox" id="enable_ontime">
+  <input id="ontime" name="on" style="width:3em"> min
+
+  $hiddenInput
+
+  </fieldset>
+</form>
+</div>
+
+<hr>
+
+<div class="ui-state-error ui-corner-all" id="error" style="padding: 5px;display:none;">
+    <span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
+    <strong>SQL Error:</strong>
+    <pre>
+$errorcol_con$errorcol1$errorcol0
+    </pre>
+  </p>
+</div>
+
+<div id="chart_area" style='position:relative'>
+<div id='chart_div' class="print" style="height:400px;width:99%;margin-left:0.5%;"></div>
+<div id='print_chart' style='position:absolute;top:10px;right:40px;'></div>
+</div>
+
+<div id="shorturl" align="right">
+$tinyurl
+</div>
+
+<hr>
+
+<input type="button" onclick="$('#spoiler0').toggle(300);" value="Legend"/>
+<div id="spoiler0" style="display:none">
+<dl>
+  <dt>&r = 1</dt><dd>trigger rate</dd>
+  <dt>&r = 2</dt><dd>rate after cleaning</dd>
+  <dt>&r = 3</dt><dd>rate after quality cuts</dd>
+  <dt>&r = 4</dt><dd>rate after background cuts</dd>
+  <dt>&r = 5</dt><dd>background rate (fOnTimeAfterCuts)</dd>
+  <dt>&r = 6</dt><dd>excess rate</dd>
+  <dt>&r = 7</dt><dd>27 second events</dd>
+  <dt>&r = 8</dt><dd>threshold 500</dd>
+  <dt>&r = 9</dt><dd>threshold 750</dd>
+  <dt>&r = 10</dt><dd>threshold 1000</dd>
+  <dt>&r = 11</dt><dd>threshold 1250</dd>
+  <dt>&r = 12</dt><dd>threshod 2500</dd>
+  <dt>&r = 13</dt><dd>threshold 5000</dd>
+  <dt>&r = 14</dt><dd>threshold 10000</dd>
+  <dt>&r = 15</dt><dd>Average of calculated EffOnTime and FTM OnTime</dd>
+  <dt>&r = 16</dt><dd>Zenith angle corrected R750</dd>
+  <dt>&r = 17</dt><dd>Event rate after background cuts (Total caclulated ontime)</dd>
+  <dt>&r = 18</dt><dd>Average of FTM effective on time</dd>
+  <dt>&r = 19</dt><dd>Sum of FTM OnTime divided by sum of FTM Elapsed time</dd>
+  <dt>&r = 20</dt><dd>Rate after cleaning corrected for 27sec events run-wise corrected for zenith angle and threshold</dd>
+  <dt>&r = 21</dt><dd>Physics trigger rate</dd>
+  <dt>&r = 22</dt><dd>Physics trigger rate corrected for 27sec events</dd>
+  <dt>&r = 23</dt><dd>Rate after cleaning corrected for 27sec events</dd>
+  <dt>&r = 24</dt><dd>Rate after background cuts runwise corrected for zenith angle and threshold</dd>
+  <dt>&r = 25</dz><dd>Rate after quallity cuts runwise corrected for zenith angle and threshold</dd>
+  <dt>&r = 42</dz><dd>Plot average of &y=... (profile histogram with &y as weights)</dd>
+  <dt>&r = 43</dz><dd>Plot sum of &y=... (histogram with &y as weights)</dd>
+  <dt>&r = 44</dz><dd>Plot user defined variable &y=...</dd>
+  <dt>&r = 45</dz><dd>Plot a histogram (counts) [&y=... can be used to specify what is counted != NULL, if omitted COUNT(*)]</dd>
+  <dt>&r = 46</dz><dd>Plot a histogram (log10(counts)) [&y=... can be used to specify what is counted != NULL, if omitted COUNT(*)]</dd>
+  <P>
+  <dt>&g = 1</dt><dd>Binning in moon periods</dd>
+  <dt>&g = 2</dt><dd>Nightly binning</dd>
+  <dt>&g = 3</dt><dd>Yearly binning</dd>
+  <dt>&g = 4</dt><dd>Season binning (lower culmination to lower culmination)</dd>
+  <dt>&g = 5</dt><dd>Run wise display (might be slow!)</dd>
+  <dt>&g = 6</dt><dd>Binning in fZenithDistanceMean [default bin-width: 5]</dd>
+  <dt>&g = 7</dt><dd>Binning in ThresholdMinSet [default bin-width: 50]</dd>
+  <dt>&g = 42</dt><dd>Use &x=... for x-axis binning [default bin-width: 1]</dd>
+  <P>
+  <dt>&b=...</dt><dd>Restrict data range (begin) [eg. &b=2011-10-01]</dd>
+  <dt>&e=...</dt><dd>Restrict data range (end) [eg. &e=2011-10-01]</dd>
+  <dt>&print</dt><dd>Show the plot only [&print] </dd>
+  <dt>&s=...</dt><dd>Restrict to given source id [eg. &s=5] </dd>
+  <dt>&t=...</dt><dd>Choose table with analysis results (ISDC, LP:default) [eg. &t=ISDC] </dd>
+  <dt>&cut=...</dt><dd>Additional where statement to be added with AND [eg. &cut=fZenithDistance&lt;35]</dd>
+  <dt>&min=...</dt><dd>y-axis minimum [eg. &min=0]</dd>
+  <dt>&max=...</dt><dd>y-axis maximum [eg. &max=0]</dd>
+  <dt>&no-errors</dt><dd>suppress error bars [eg. &no-errors]</dd>
+  <dt>&no-hist</dt><dd>do not show histogram as bars [eg. &no-hist]</dd>
+  <dt>&x=...</dt><dd>A x-axis binned in ... [forces &g=42, eg. &x=fZenithDistance]</dd>
+  <dt>&w=...</dt><dd>Bin width for &g=6/7/42 [eg. &w=2]</dd>
+  <dt>&y=...</dt><dd>x-axis variable, to be used with &r=42/43/44[/45] [eg. &y=fOnTime]</dd>
+  <dt>&avg=...</dt><dd>short for &y=... [forces &r=42, eg. &y=fOnTime]</dd>
+  <dt>&sum=...</dt><dd>short for &y=... [forces &r=43, eg. &y=fOnTime]</dd>
+  <dt>&hist=...</dt><dd>short for &x=...  [forces &r=45, eg. &y=fOnTime]</dd>
+</dl>
+</div>
+
+<hr>
+
+<input type="button" onclick="$('#spoiler1').toggle(300);" value="SQL Query"/>
+<div id="spoiler1" style="display:none">
+<pre>
+Database = $database
+<hr>
+$querycol1
+
+<hr>
+$querycol0
+
+<tt><font color="blue"><b>Roundtrip query time:</B></font> $timeMeasured ms</tt>
+</pre>
+</div>
+
+<hr>
+
+$data
+
+</body>
+</html>
+EOT;
+
+?>
