0)
        {
            foreach ($checkgroup as $key => $element)
                if ($element==-1)
                    $query0 .=  $key . " as '" . $alias[$key] . "' " . ", ";
            //--------------------------------------------------
            $query0 .= "SUM(fRunTime)/3600 as '" . $alias["SUM(fRunTime)/3600"] . "', ";
            //--------------------------------------------------
            $query0 .= " SUM(fNumEvents) as '" . $alias["SUM(fNumEvents)"] . "', ";
            $query0 .= " Min(fZenithDistanceMin) as '" . $alias["Min(fZenithDistanceMin)"] . "', ";
            $query0 .= " Max(fZenithDistanceMax) as '" . $alias["Max(fZenithDistanceMax)"] . "', ";
            $query0 .= " COUNT(*) as '# Sequ' ";
        }
        else
        {
            if ($statusgroups>0)
            {
                foreach ($checkstatusgroup as $key => $element)
                    if ($element==-1)
                        $query0 .= " (if(IsNull(" . $key . "), if(isnull(fStartTime), 'not done', if(isnull(fFailedTime),if(isnull(" . $needs[$key] . "),'not done',if(date_sub(Now(),interval 12 hour) < fStartTime,'running','crashed')),if(isnull(" . $needs[$key] . "),'not done','failed'))) ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "', ";
//                        $query0 .= " (if(IsNull(" . $key . "), 'not done' ,if(" . $key . "='1970-01-01 00:00:00','dont do','done'))) as '" . $alias[$key] . "', ";
                $query0 .= " COUNT(*) as '# Sequ'";
            }
            else
            {
                $query0 .= " " . $fromtable . ".fSequenceFirst as '" . $alias["fSequenceFirst"] . "' ";
                if (!empty($_GET["fLinks"]))
                {
                    $query0 .= ", CONCAT('r ' ";
                    //                        $query0 .= " as " . $alias["fSequenceFirst"];
                    $query0 .= ", ' cl '";
                    $query0 .= ", ' c '";
                    $query0 .= ", ' sl '";
                    $query0 .= ", ' s '";
                    $query0 .= ", ' ', 'f  ' ";
                    $query0 .= ", ' i ') ";
                    $query0 .= " as 'Links'";
                }
                foreach ($_GET as $key => $element)
                    if ($_GET[$key]=="On")
                        if ($key!="fLinks" && $key!="fOff" && $key!="fOnlyOff")
                            if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
                                $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
            }
        }
        $query0 .= " FROM " . $fromtable;
        $query0 .= " LEFT JOIN SequenceProcessStatus ON Sequences.fSequenceFirst=SequenceProcessStatus.fSequenceFirst ";
        $query0 .= " LEFT JOIN Calibration ON Sequences.fSequenceFirst=Calibration.fSequenceFirst ";
        $query0 .= " LEFT JOIN Star ON Sequences.fSequenceFirst=Star.fSequenceFirst ";
        foreach ($_GET as $key => $element)
            if (($_GET[$key]=="On" || $groups>0))// && !empty(GetJoin($fromtable,$key)))
                $query0 .= GetJoin($fromtable,$key);
        if ($_GET["fTest"]!="On")
        {
            if ($_GET["fSourceName"]!="On")
                $query0 .= " LEFT JOIN Source ON Sequences.fSourceKEY=Source.fSourceKEY ";
            $query0 .= " WHERE fTest='no'";
        }
        if ($_GET["fOff"]=="Off")
        {
            if (strpos($query0, " WHERE ")==FALSE)
                $query0 .= " WHERE ";
            else
                $query0 .= " AND ";
            $query0 .= " NOT (fSourceName like '%Off%')";
        }
        if ($_GET["fOnlyOff"]=="On")
        {
            if (strpos($query0, " WHERE ")==FALSE)
                $query0 .= " WHERE ";
            else
                $query0 .= " AND ";
            $query0 .= " fSourceName like '%Off%'";
        }
        foreach ($checkwhere as $key => $element)
        {
            if (empty($element) || $element<=0)
                continue;
            if (strpos($query0, " WHERE ")==FALSE)
                $query0 .= " WHERE ";
            else
                if ($element!=-1)
                    if (strrpos($query0, " AND ")!=strlen($query0)-5)
                        $query0 .= " AND ";
            if ($element!=-1)
                $query0 .= GetCheck($fromtable, $key) . "=" . $element;
        }
        if (strpos($query0, " WHERE ")==FALSE)
            $query0 .= " WHERE ";
        else
            $query0 .= " AND ";
        $query0 .= StatusQuery("fSequenceFileWritten", $needs);
        $query0 .= StatusQuery("fAllFilesAvail", $needs);
        $query0 .= StatusQuery("fCallisto", $needs);
        $query0 .= StatusQuery("fFillCallisto", $needs);
        $query0 .= StatusQuery("fStar", $needs);
        $query0 .= StatusQuery("fFillStar", $needs);
        if (!empty($_GET["fRunMin"]) && !empty($_GET["fRunMax"]))
            $query0 .= "Sequences.fSequenceFirst BETWEEN " . $_GET["fRunMin"] . " AND " . $_GET["fRunMax"] . " ";
        else
            $query0 = substr($query0, 0, -4);
        if ((!empty($_GET["fZDMin"]) || $_GET["fZDMin"]==0) && !empty($_GET["fZDMax"]))
            $query0 .= "AND (fZenithDistanceMin >= " . $_GET["fZDMin"] . " AND fZenithDistanceMax <= " . $_GET["fZDMax"] . ") ";
        if (!empty($_GET["fSourceN"]))
            $query0 .= " AND fSourceName REGEXP \"^" . $_GET["fSourceN"] . "\" ";
        if (!empty($_GET["fStartDate"]))
        {
            if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
                $query0 .= " AND ";
            $startdate=substr($_GET["fStartDate"], 0, 10);
            if ($startdate=="0000-00-00")
                $query0 .=" fRunStart >= '" . $startdate . " 00:00:00' ";
            else
                $query0 .= " fRunStart >= ADDDATE('" . $startdate . " 13:00:00', INTERVAL -1 DAY) ";
        }
        if (!empty($_GET["fStopDate"]))
        {
            if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
                $query0 .= " AND ";
            $stopdate=substr($_GET["fStopDate"], 0, 10);
            $query0 .= " fRunStart < '" . $stopdate . " 13:00:00' ";
        }
        if (!empty($_GET["fStarStart"]))
        {
            if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
                $query0 .= " AND ";
            $starstart=substr($_GET["fStarStart"], 0, 10);
            $query0 .=" fStar >= '" . $starstart . " 00:00:00' ";
        }
        if (!empty($_GET["fStarStop"]))
        {
            if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
                $query0 .= " AND ";
            $starstop=substr($_GET["fStarStop"], 0, 10);
            $query0 .= " fStar < '" . $starstop . " 23:59:59' ";
        }
        if ($groups>0)
        {
            $query0 .= " GROUP BY ";
            $num = $groups;
            foreach ($checkgroup as $key => $element)
                if ($element==-1)
                {
                    $query0 .= GetCheck($fromtable,$key);
                    if ($num-->1)
                        $query0 .= ", ";
                }
        }
        if ($statusgroups>0)
        {
            $query0 .= " GROUP BY ";
            $num = $statusgroups;
            foreach ($checkstatusgroup as $key => $element)
                if ($element==-1)
                {
                    $query0 .= $alias[$key];
                    if ($num-->1)
                        $query0 .= ", ";
                }
        }
        if (!empty($_GET["fSortBy"]))
        {
            $val=substr($_GET["fSortBy"], 0, -1);
            $query0 .= " ORDER BY " . GetTable($fromtable,$val) . " ";
            if (substr($_GET["fSortBy"], -1)=="-")
                $query0 .= "DESC";
        }
        if (empty($_GET["fSortBy"]) && $groups==0 && $statusgroups==0)
            $query0 .= "ORDER BY Sequences.fSequenceFirst DESC ";
        if (empty($_GET["fNumStart"]))
            $_GET["fNumStart"]=0;
        if (empty($_GET["fSendTxt"]))
            $query0 .= " LIMIT " . $_GET["fNumStart"] . ", " . $_GET["fNumResults"];
        return $query0;
    }
    function InitGet($_GET)
    {
        // Find out whether it is the first call to the php script
        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
        if (empty($_GET["fNumResults"]))
            $_GET["fNumResults"]="100";
        if (empty($_GET["fRunStart"]))
            $_GET["fRunStart"]=$first?"On":"";
        if (empty($_GET["fRunTime/60"]))
            $_GET["fRunTime/60"]=$first?"On":"";
        if (empty($_GET["fZenithDistanceMin"]))
            $_GET["fZenithDistanceMin"]=$first?"On":"";
        if (empty($_GET["fZenithDistanceMax"]))
            $_GET["fZenithDistanceMax"]=$first?"On":"";
        if (empty($_GET["fSourceName"]))
            $_GET["fSourceName"]=$first?"On":"";
        if (empty($_GET["fObservationModeName"]))
            $_GET["fObservationModeName"]=$first?"On":"";
        if (empty($_GET["fUnsuitableInner"]))
            $_GET["fUnsuitableInner"]=$first?"On":"";
        if (empty($_GET["fUnreliableInner"]))
            $_GET["fUnreliableInner"]=$first?"On":"";
        if (empty($_GET["fIsolatedInner"]))
            $_GET["fIsolatedInner"]=$first?"On":"";
        if (empty($_GET["fIsolatedMaxCluster"]))
            $_GET["fIsolatedMaxCluster"]=$first?"On":"";
//        if (empty($_GET["fArrTimeMeanInner"]))
//            $_GET["fArrTimeMeanInner"]=$first?"On":"";
        if (empty($_GET["fArrTimeRmsInner"]))
            $_GET["fArrTimeRmsInner"]=$first?"On":"";
        if (empty($_GET["fMeanPedRmsInner"]))
            $_GET["fMeanPedRmsInner"]=$first?"On":"";
        if (empty($_GET["fPulsePosMean"]))
            $_GET["fPulsePosMean"]=$first?"On":"";
        if (empty($_GET["fConvFactorInner"]))
            $_GET["fConvFactorInner"]=$first?"On":"";
        if (empty($_GET["fInhomogeneity"]))
            $_GET["fInhomogeneity"]=$first?"On":"";
        if (empty($_GET["fPSF"]))
            $_GET["fPSF"]=$first?"On":"";
        if (empty($_GET["fMuonNumber"]))
            $_GET["fMuonNumber"]=$first?"On":"";
        if (empty($_GET["fEffOnTime/fRunTime"]))
            $_GET["fEffOnTime/fRunTime"]=$first?"On":"";
        if (empty($_GET["fMuonRate"]))
            $_GET["fMuonRate"]=$first?"On":"";
        if (empty($_GET["fDataRate"]))
            $_GET["fDataRate"]=$first?"On":"";
//        if (empty($_GET["fMaxHumidity"]))
//            $_GET["fMaxHumidity"]=$first?"On":"";
        if (empty($_GET["fBrightnessMed"]))
            $_GET["fBrightnessMed"]=$first?"On":"";
        if (empty($_GET["fNumStarsMed"]))
            $_GET["fNumStarsMed"]=$first?"On":"";
        if (empty($_GET["fNumStarsCorMed"]))
            $_GET["fNumStarsCorMed"]=$first?"On":"";
        if (empty($_GET["fOff"]))
            $_GET["fOff"]=$first?"On":"";
        if (empty($_GET["fLinks"]))
            $_GET["fLinks"]=$first?"On":"";
        if (empty($_GET["fOnlyOff"]))
            $_GET["fOnlyOff"]=$first?"Off":"";
        InitFindOffData($_GET, $first);
    }
    function PrintForm($_GET, $host, $user, $pw, $db, $limitsmean, $limitsmin, $limitsmax, $alias)
    {
        printf("
\n");
        printf("\n");
    }
    function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs)
    {
        $db_id = mysql_pconnect($host, $user, $pw);
        if ($db_id==FALSE)
        {
            printf("mysql_connect returned the following error: %s\n", mysql_error());
            die("");
        }
        mysql_select_db($db);
        $query0 = CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs);
        $result0 = mysql_query($query0, $db_id);
        if ($result0)
        {
            if ($html=="1" || $html=="2")
            {
                PrintMagicTable($result0, $alias, $rightalign, $limitsmean, $limitsmin, $limitsmax, "yes", $_GET);
                foreach($_POST as $key => $val)
                    if ($val=="On")
                    {
                        if (ereg("ON$", $key))
                            $sequon.=str_replace("ON", " ", $key);
                        if (ereg("Off$", $key))
                            $sequoff.=str_replace("Off", " ", $key);
                    }
                printf("\n");
                    $vals=array("on", "off");
                    foreach($vals as $num => $val)
                    {
                        if (empty(${$val}))
                            continue;
                        GetSequenceValues($db_id, ${$val}, $val, $values);
                        if ($values["Min(fNumStarsCorMed)"][$val]<$numstarscorlimit)
                            printf("%s: one of your %s-sequences has less than %s correlated stars (%s) ",
                                   $color["WARN"], "WARN", $val, $numstarscorlimit, $values["Min(fNumStarsCorMed)"][$val]);
                        if ($values["Min(fNumStarsMed)"][$val]<$numstarslimit)
                            printf("%s: one of your %s-sequences has less than %s identified stars (%s) ",
                                   $color["WARN"], "WARN", $val, $numstarslimit, $values["Min(fNumStarsMed)"][$val]);
                        if ($values["Min(fRunTime)/60"][$val]<$runtimelimit)
                            printf("%s: one of your %s-sequences is shorter than %s min (%s min) ",
                                   $color["INFO"], "INFO", $val, $runtimelimit, $values["Min(fRunTime)/60"][$val]);
                        if ($values["Max(fInhomogeneity)"][$val]>$inhomlimit)
                            printf("%s: one of your %s-sequences has an inhomogeneity larger than %s (%s) ",
                                   $color["WARN"], "WARN", $val, $inhomlimit, $values["Max(fInhomogeneity)"][$val]);
                        if ($values["Max(fUnsuitableInner)"][$val]>$unsuitablemaxlimit)
                            printf("%s: one of your %s-sequences has more than %s unsuitable inner pixel (%s) ",
                                   $color["WARN"], "WARN", $val, $unsuitablemaxlimit, $values["Max(fUnsuitableInner)"][$val]);
                        if ($values["Max(fIsolatedInner)"][$val]>$isolatedlimit)
                            printf("%s: one of your %s-sequences has more than %s isolated inner pixel (%s) ",
                                   $color["WARN"], "WARN", $val, $isolatedlimit, $values["Max(fIsolatedInner)"][$val]);
                        if ($values["Max(fIsolatedMaxCluster)"][$val]>$imclimit)
                            printf("%s: one of your %s-sequences has more than %s isolated max cluster (%s) ",
                                   $color["WARN"], "WARN", $val, $imclimit, $values["Max(fIsolatedMaxCluster)"][$val]);
                    }
                    if (!empty($on) && $values["Max(fMeanPedRmsInner)"]["on"]>$values["Avg(fMeanPedRmsInner)"]["on"]+$pedrmsrms)
                        printf("%s: one of your on-sequences has a PedRms larger than %s (%s) ",
                               $color["WARN"], "WARN", $values["Avg(fMeanPedRmsInner)"]["on"]+$pedrmsrms, $values["Max(fMeanPedRmsInner)"]["on"]);
                    if (!empty($off) && $values["Max(fMeanPedRmsInner)"]["off"]>$values["Avg(fMeanPedRmsInner)"]["on"]+$pedrmsrms)
                        printf("%s: one of your off-sequences has a PedRms larger than %s (%s) ",
                               $color["WARN"], "WARN", $values["Avg(fMeanPedRmsInner)"]["on"]+$pedrmsrms, $values["Max(fMeanPedRmsInner)"]["off"]);
                    if (!empty($off) && $values["Min(fMeanPedRmsInner)"]["off"]<$values["Avg(fMeanPedRmsInner)"]["on"]-$pedrmsrms)
                        printf("%s: one of your off-sequences has a PedRms smaller than %s (%s) ",
                               $color["WARN"], "WARN", $values["Avg(fMeanPedRmsInner)"]["on"]-$pedrmsrms, $values["Min(fMeanPedRmsInner)"]["off"]);
                    $scale=$values["Sum(fRunTime)/60"]["on"]/$values["Sum(fRunTime)/60"]["off"];
                    if ($scale > $scalelimit)
                        printf("%s: Your scale factor is larger than %s (%0.2f). Try to find more offdata!",
                               $color["WARN"], "WARN", $scalelimit, $scale);
                    /*
                    if (str_word_count($sourceson) > 1)
                        printf(" %s: You have selected more than one (%s) on source",
                               $color["WARN"], "WARN", str_word_count($sourceson));
                    */
                    $doubleseq=0;
//                    printf("finding: %s %s: You have selected sequences (%s) as On AND Off",
                               $color["ERROR"], "ERROR", $doubleseq);
                        $numerr=$numerr+1;
                    }
                    if ($numrealkeys>1)
                    {
                        printf(" %s: You have selected more than one (%s) on source",
                               $color["ERROR"], "ERROR", $numrealkeys);
                        $numerr=$numerr+1;
                    }
                    if ($numobskeys>1)
                    {
                        printf(" %s: You have selected more than one (%s) different observation modes for your on sequences",
                               $color["ERROR"], "WARN", $numobskeys);
//                        $numerr=$numerr+1;
                    }
                    if (empty($_POST["fObservationModeKEY"]) && !empty($_GET["obsmode"]))
                        $_POST["fObservationModeKEY"]=$_GET["obsmode"];
                    if ($_POST["fObservationModeKEY"]==3 && empty($off))
                    {
                        printf(" %s: You have selected on/off mode, but you haven't chosen any off sequences.",
                               $color["ERROR"], "WARN");
//                        $numerr=$numerr+1;
                    }
                    if (empty($realsourcekey))
                    {
                        printf(" %s: The source you selected doesn't have a real sourcekey yet. Please insert fRealSourceKEY in the DB for %s",
                               $color["ERROR"], "ERROR", $sourceson);
                        $numerr=$numerr+1;
                    }
                    if (empty($_POST["fObservationModeKEY"]))
                    {
                        printf(" %s: You have to choose an observation mode.",
                               $color["ERROR"], "ERROR");
                        $numerr=$numerr+1;
                    }
                    if (empty($_POST["fUserKEY"]))
                    {
                        printf(" %s: You have to choose your username.",
                               $color["ERROR"], "ERROR");
                        $numerr=$numerr+1;
                    }
                    if (empty($_POST["name"]))
                    {
                        printf(" %s: You have to choose a name.",
                               $color["ERROR"], "ERROR");
                        $numerr=$numerr+1;
                    }
                    if (empty($_POST["comment"]))
                    {
                        printf(" %s: You have to comment your dataset.",
                               $color["ERROR"], "ERROR");
                        $numerr=$numerr+1;
                    }
                    //                printf("  \n");
                    printf("
");
                    printf("SequencesOn: %s
");
                    if (empty($_POST["name"]) && !empty($_GET["name"]))
                        $_POST["name"]=$_GET["name"];
                    if (empty($_POST["comment"]) && !empty($_GET["comment"]))
                        $_POST["comment"]=$_GET["comment"];
                    if (empty($_POST["fUserKEY"]) && !empty($_GET["username"]))
                        $_POST["fUserKEY"]=$_GET["username"];
                    printf("Name:  
\n", $_POST["name"]);
                    printf("Comment:  
\n", $_POST["comment"]);
                    $query   = "SELECT fObservationModeKEY, fObservationModeName FROM ObservationMode ORDER BY fObservationModeName";
                    $result  = mysql_query($query);
                    if (!$result)
                        printf("-N/A-");
                    $numrows = mysql_num_rows($result);
                    printf("ObservationMode 
\n");
                    while ($row = mysql_fetch_row($result))
                    {
                        if (!empty($_POST["fObservationModeKEY"]) && $_POST["fObservationModeKEY"]==$row[0])
                            printf("%s \n", $row[0], $row[1]);
                        else
                            printf("%s \n", $row[0], $row[1]);
                    }
                    printf(" \n");
                    mysql_free_result($result);
                    $query   = "SELECT fUserKEY, fUserName FROM User ORDER BY fUserKEY";
                    $result  = mysql_query($query);
                    if (!$result)
                        printf("-N/A-");
                    $numrows = mysql_num_rows($result);
                    printf("UserName 
\n");
                    while ($row = mysql_fetch_row($result))
                    {
                        if (!empty($_POST["fUserKEY"]) && $_POST["fUserKEY"]==$row[0])
                            printf("%s \n", $row[0], $row[1]);
                        else
                            printf("%s \n", $row[0], $row[1]);
                    }
                    printf(" \n");
                    mysql_free_result($result);
                    printf("Remark: only datasets without errors can be inserted.
");
                    if ($numerr!=0)
                        printf("Your dataset has %s error(s).
", $numerr);
                    printf("
insert\n");
                    printf("
Dataset proposed DataSet#:  %s SequencesOn:  %s SequencesOff:  %s Scale:  %0.2f SourcenamesOn[%s]:  %s SourcenamesOff[%s]:  %s 
\n");
                    printf("
\n");
                    printf("Value On ");
                    if (!empty($off))
                        printf("Off %s \n", $name);
                        foreach($vals as $num => $val)
                            if (!empty(${$val}))
                                printf("%s \n", $varname[$val]);
                        printf("
\n");
                }
                printf("
\n");
                printf("-- \n");
                foreach($values as $name => $varname)
                        printf("%s \n", $name);
                $vals=array("on", "off");
                foreach($vals as $num => $val)
                {
                    GetSequenceValues($db_id, ${$val}, $val, $values);
                    printf(" \n");
                    printf("On \n");
                    foreach($values as $name => $varname)
                        printf("%s \n", $varname[$val]);
                }
                printf(" 
\n");
                */
                printf("\n");
                printf(" \n");
                printf(" \n");
                printf("\n");
            }
            else
                PrintText($result0);
            mysql_free_result($result0);
        }
        mysql_close($db_id);
        PrintSubmittedQuery($query0, $html, $db, "");
    }
    include ("include.php");
    include ("menu.php");
    include ("db.php");
    include ("magicdefs.php");
    ini_set("display_errors", "On");
    ini_set("mysql.trace_mode", "On");
    $sitepw="\$1\$ml/Gld67\$zOvhC4vFrLCkbAzQs2swo1";
    $siteuser="dcdb";
    if (!isset($_SERVER['PHP_AUTH_USER']) || crypt($_SERVER['PHP_AUTH_PW'], $sitepw)!=$sitepw || $_SERVER['PHP_AUTH_USER']!=$siteuser)
    {
        header('WWW-Authenticate: Basic realm="Build Datasets"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Cancelled.';
        return;
    }
    else
    {
//    echo "Hello {$_SERVER['PHP_AUTH_USER']}.
";
//    echo "You entered {$_SERVER['PHP_AUTH_PW']} as your password.
";
//    printf("pw: %s", crypt($_SERVER['PHP_AUTH_PW']));
        if (crypt($_SERVER['PHP_AUTH_PW'], $sitepw)!=$sitepw || $_SERVER['PHP_AUTH_USER']!=$siteuser)
        {
            printf("