Index: trunk/MagicSoft/Mars/datacenter/db/builddatasets.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/builddatasets.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/builddatasets.php	(revision 9498)
@@ -1,5 +1,23 @@
 <?php
-{
-    function CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs)
+
+    function PrintDataSetFile()
+    {
+            printf("AnalysisNumber: 1\n\n");
+            printf("SeqencesOn: %s \n", $_SESSION["sequon"]);
+            if ($_SESSION["sequoff"]!=" ")
+                printf("SeqencesOff: %s \n\n", $_SESSION["sequoff"]);
+            else
+                printf("\n");
+
+            printf("SourceName: %s \n", $_SESSION["realsourcename"]);
+            printf("Catalog: /magic/datacenter/setup/magic_favorites_dc.edb \n");
+            if ($_SESSION["sequoff"]==" ")
+                printf("WobbleMode: On \n\n");
+            printf("RunTime: %s \n", $_SESSION["runtime"]);
+            printf("Name: %s \n", $_SESSION["name"]);
+            printf("Comment: %s \n", $_SESSION["comment"]);
+    }
+
+    function CreateQuery($alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs)
     {
         $fromtable="Sequences";
@@ -15,5 +33,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0)
@@ -37,5 +55,4 @@
                     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'";
@@ -45,8 +62,8 @@
             {
                 $query0 .= " " . $fromtable . ".fSequenceFirst as '" . $alias["fSequenceFirst"] . "' ";
-                if (!empty($_GET["fLinks"]))
+                if (!empty($_SESSION["fLinks"]))
                 {
                     $query0 .= ", CONCAT('<A&ws;HREF=\"runinfo-aio.php?',  'fRunStart=On', '&amp;fZenithDistance=On', '&amp;fRunMin=', Sequences.fSequenceFirst, '&amp;fMeanTriggerRate=On', '&amp;fTest=On', '&amp;fRunTypeName=On', '&amp;fRunMax=', fSequenceLast, '&amp;fNumEvents=On', '&amp;fSourceName=On&amp;', 'fExcludedFDAKEY=1', '&amp;fSequenceFirst=On', '&amp;fRawFileAvail=On', '&amp;fCCFileAvail=On', '&amp;fCaCoFileAvail=On', '&amp;fNumResults=500\">r</A>' ";
-                    //                        $query0 .= " as " . $alias["fSequenceFirst"];
+                    //$query0 .= " as " . $alias["fSequenceFirst"];
                     $query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/callisto/' , LEFT(LPAD(CONCAT(Sequences.fSequenceFirst, '.'), 9,'0'),4), '/', LPAD(CONCAT(Sequences.fSequenceFirst, '/'), 9,'0'), 'callisto', LPAD(CONCAT(Sequences.fSequenceFirst , '.html'), 13,'0') , '\">cl</A>'";
                     $query0 .= ", '&nbsp;<A&ws;HREF=\"http://www.astro.uni-wuerzburg.de/datacenter/callisto/' , LEFT(LPAD(CONCAT(Sequences.fSequenceFirst, '.'), 9,'0'),4), '/', LPAD(CONCAT(Sequences.fSequenceFirst, '/'), 9,'0'), '\">c</A>'";
@@ -58,9 +75,10 @@
                 }
 
-                foreach ($_GET as $key => $element)
-                    if ($_GET[$key]=="On")
+                foreach ($_SESSION as $key => $element)
+                    if ($_SESSION[$key]=="On")
                         if ($key!="fLinks" && $key!="fOff" && $key!="fOnlyOff")
-                            if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
-                                $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
+                            if (!(ereg("^[0-9]*ON$", $key) || ereg("^[0-9]*Off$", $key)))
+                                if (empty($checkwhere[$key]) || $checkwhere[$key]==0)
+                                    $query0 .= ", " . $key . " as '" . $alias[$key] . "' ";
             }
         }
@@ -72,17 +90,53 @@
         $query0 .= " LEFT JOIN Star USING(fSequenceFirst,fTelescopeNumber) ";
 
-        foreach ($_GET as $key => $element)
-            if (($_GET[$key]=="On" || $groups>0))// && !empty(GetJoin($fromtable,$key)))
+        foreach ($_SESSION as $key => $element)
+            if (($_SESSION[$key]=="On" || $groups>0))// && !empty(GetJoin($fromtable,$key)))
                 $query0 .= GetJoin($fromtable,$key);
 
-        if ($_GET["fTest"]!="On")
-        {
-            if ($_GET["fSourceName"]!="On")
-                $query0 .= " LEFT JOIN Source USING(fSourceKEY) ";
-            $query0 .= " WHERE fTest='no'";
-        }
-
-        if ($_GET["fOff"]=="Off")
-        {
+        if ($_SESSION["DisplaySelected"]!="yes" || ($_SESSION["sequon"]==" " && $_SESSION["sequoff"]==" "))
+        {
+            if ($_SESSION["fTest"]!="On")
+            {
+                if ($_SESSION["fSourceName"]!="On")
+                    $query0 .= " LEFT JOIN Source USING(fSourceKEY) ";
+                $query0 .= " WHERE fTest='no'";
+            }
+
+            if ($_SESSION["fOff"]=="Off")
+            {
+                if (strpos($query0, " WHERE ")==FALSE)
+                    $query0 .= " WHERE ";
+                else
+                    $query0 .= " AND ";
+
+                $query0 .= " NOT (fSourceName like '%Off%')";
+            }
+
+            if ($_SESSION["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 ";
@@ -90,245 +144,129 @@
                 $query0 .= " AND ";
 
-            $query0 .= " NOT (fSourceName like '%Off%')";
-        }
-
-        if ($_GET["fOnlyOff"]=="On")
-        {
-            if (strpos($query0, " WHERE ")==FALSE)
-                $query0 .= " WHERE ";
+            $query0 .= StatusQuery("fSequenceFileWritten", $needs, $timelimits);
+            $query0 .= StatusQuery("fAllFilesAvail", $needs, $timelimits);
+            $query0 .= StatusQuery("fCallisto", $needs, $timelimits);
+            $query0 .= StatusQuery("fFillCallisto", $needs, $timelimits);
+            $query0 .= StatusQuery("fStar", $needs, $timelimits);
+            $query0 .= StatusQuery("fFillStar", $needs, $timelimits);
+
+            if (!empty($_SESSION["fRunMin"]) && !empty($_SESSION["fRunMax"]))
+                $query0 .= "Sequences.fSequenceFirst BETWEEN " . $_SESSION["fRunMin"] . " AND " . $_SESSION["fRunMax"] . " ";
             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 ";
+                $query0 = substr($query0, 0, -4);
+
+            if ((!empty($_SESSION["fZDMin"]) || $_SESSION["fZDMin"]==0) && !empty($_SESSION["fZDMax"]))
+                $query0 .= "AND (fZenithDistanceMin >= " . $_SESSION["fZDMin"] . " AND fZenithDistanceMax <= " . $_SESSION["fZDMax"] . ") ";
+
+            if (!empty($_SESSION["fSourceN"]))
+                $query0 .= " AND fSourceName REGEXP \"^" . $_SESSION["fSourceN"] . "\" ";
+
+            if (!empty($_SESSION["fStartDate"]))
+            {
+                if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                    $query0 .= " AND ";
+
+                $startdate=substr($_SESSION["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($_SESSION["fStopDate"]))
+            {
+                if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                    $query0 .= " AND ";
+
+                $stopdate=substr($_SESSION["fStopDate"], 0, 10);
+                $query0 .= " fRunStart < '" . $stopdate . " 13:00:00' ";
+            }
+
+            if (!empty($_SESSION["fStarStart"]))
+            {
+                if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                    $query0 .= " AND ";
+
+                $starstart=substr($_SESSION["fStarStart"], 0, 10);
+                $query0 .=" fStar >= '" . $starstart . " 00:00:00' ";
+            }
+
+            if (!empty($_SESSION["fStarStop"]))
+            {
+                if (strpos(strrev($query0), " DNA ")!=0 || !strpos(strrev($query0), " DNA "))
+                    $query0 .= " AND ";
+
+                $starstop=substr($_SESSION["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 .= ", ";
+                    }
+            }
+
+        }
         else
-            $query0 .= " AND ";
-
-        $query0 .= StatusQuery("fSequenceFileWritten", $needs, $timelimits);
-        $query0 .= StatusQuery("fAllFilesAvail", $needs, $timelimits);
-        $query0 .= StatusQuery("fCallisto", $needs, $timelimits);
-        $query0 .= StatusQuery("fFillCallisto", $needs, $timelimits);
-        $query0 .= StatusQuery("fStar", $needs, $timelimits);
-        $query0 .= StatusQuery("fFillStar", $needs, $timelimits);
-
-        if (!empty($_GET["fRunMin"]) && !empty($_GET["fRunMax"]))
-            $query0 .= "Sequences.fSequenceFirst BETWEEN " . $_GET["fRunMin"] . " AND " . $_GET["fRunMax"] . " ";
+        {
+            $displsequ=str_replace("  ", " ", $_SESSION["sequon"].$_SESSION["sequoff"]);
+            $displsequ=ereg_replace("^ ", "(", $displsequ);
+            $displsequ=ereg_replace(" $", ")", $displsequ);
+            $displsequ=str_replace(" ",  ",", $displsequ);
+
+            $query0 .= "WHERE fSequenceFirst IN " . $displsequ;
+        }
+
+        if (!empty($_SESSION["fSortBy"]))
+        {
+            $val=substr($_SESSION["fSortBy"], 0, -1);
+            $query0 .= " ORDER BY " . GetTable($fromtable,$val) . " ";
+            if (substr($_SESSION["fSortBy"], -1)=="-")
+                $query0 .= "DESC";
+        }
+
+        if (empty($_SESSION["fSortBy"]) && $groups==0 && $statusgroups==0)
+            $query0 .= " ORDER BY Sequences.fSequenceFirst DESC ";
+
+        if (empty($_SESSION["fNumStart"]))
+            $start=0;
         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)
+            $start=$_SESSION["fNumStart"];
+
+        if (empty($_SESSION["fSendTxt"]))
+            $query0 .= " LIMIT " . $start . ", " . $_SESSION["fNumResults"];
+
+            return $query0;
+    }
+
+    function PrintForm($host, $user, $pw, $db, $limitsmean, $limitsmin, $limitsmax, $alias)
     {
         printf("<center>\n");
         printf("<form action='builddatasets.php' METHOD='GET'>\n");
         printf("<input id='sh' type='hidden' name='fShowHide' value='");
-        if (!empty($_GET["fShowHide"]))
-            printf("%s", $_GET["fShowHide"]);
+        if (!empty($_SESSION["fShowHide"]))
+            printf("%s", $_SESSION["fShowHide"]);
         else
-            printf("1000000000");
+            printf("1000000010");//display Ranges
         printf("'>\n");
         printf("<img id='allbutton' src='minus.png' alt='-' onclick='showhide(\"all\")'> <b>Menu</b>&nbsp;&nbsp;&nbsp;&nbsp;\n");
@@ -370,20 +308,4 @@
         PrintButtons("builddatasets.php");
 
-        $sequon=" ";
-        $sequoff=" ";
-        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("<input name='Set' type='hidden' value='%s'>\n", $sequon);
-        printf("<input name='Set2' type='hidden' value='%s'>\n", $sequoff);
-        printf("<input name='name' type='hidden' value='%s'>\n", $_POST["name"]);
-        printf("<input name='comment' type='hidden' value='%s'>\n", $_POST["comment"]);
-        printf("<input name='obsmode' type='hidden' value='%s'>\n", $_POST["fObservationModeKEY"]);
-        printf("<input name='username' type='hidden' value='%s'>\n", $_POST["fUserKEY"]);
         printf("</form>\n");
         printf("</center>\n");
@@ -394,4 +316,62 @@
     }
 
+    function InsertDataSet($values, $dataset)
+    {
+        $insquery[0]="INSERT DataSets SET fDataSetNumber=" . $dataset . ", fUserKEY=" . $_SESSION["user"];
+        $insquery[0].=", fComment='" . $_SESSION["comment"] . "', fObservationModeKEY=" . $_SESSION["obsmode"];
+        $insquery[0].=", fDataSetName='" . $_SESSION["name"] . "', fSourceKEY= " . $_SESSION["realsourcekey"];
+        $insquery[0].=", fRunStart='" . $values["Min(fRunStart)"]["on"];
+        $insquery[0].="', fRunStop='" . $values["Max(fRunStop)"]["on"];
+        $insquery[0].="', fZenithDistanceMin=" . $values["Min(fZenithDistanceMin)"]["on"];
+        $insquery[0].=", fZenithDistanceMax=" . $values["Max(fZenithDistanceMax)"]["on"];
+        $insquery[0].=", fRunTime=" . $_SESSION["runtime"];
+        $insquery[1]="INSERT DataSetProcessStatus SET fDataSetNumber=" . $dataset . ", fDataSetInserted=Now()";
+        $i=2;
+        foreach(explode(" ", trim($_SESSION["sequon"])) as $key => $sequ)
+        {
+            $insquery[$i]="INSERT DataSetSequenceMapping SET fDataSetNumber=" . $dataset;
+            $insquery[$i].=", fSequenceFirst=" . $sequ . ", fOnOff=1";
+            $i=$i+1;
+        }
+        if (!empty($off))
+        {
+            foreach(explode(" ", trim($_SESSION["sequoff"])) as $key => $sequ)
+            {
+                $insquery[$i]="INSERT DataSetSequenceMapping SET fDataSetNumber=" . $dataset;
+                $insquery[$i].=", fSequenceFirst=" . $sequ . ", fOnOff=2";
+                $i=$i+1;
+            }
+        }
+        // insert
+        if (!empty($_SESSION["insert"]) && $numerr==0)
+        {
+            printf("<br><br>\n");
+            foreach($insquery as $num => $q)
+            {
+                printf("Inserted Query #%s: %s<br>\n", $num, $q);
+                $insresult=mysql_query($q);
+                if (mysql_errno()>0)
+                    printf("&nbsp; Errorno: %s <br>\n", mysql_errno());
+                if (mysql_error()!="")
+                    printf("&nbsp; Errormsg: %s <br>\n", mysql_error());
+                if (mysql_info()!="")
+                    printf("&nbsp; Info: %s <br>\n", mysql_info());
+                printf("&nbsp; Affected Rows: %s <br><br>\n", mysql_affected_rows());
+                mysql_free_result($insresult);
+                if (mysql_errno()>0)
+                {
+                    printf("ERROR => stop inserting. <br><br>\n");
+                    break;
+                }
+            }
+            // reset after insert
+            unset($_SESSION["insert"]);
+            unset($_SESSION["name"]);
+            unset($_SESSION["comment"]);
+        }
+        else
+            printf("<input type='button' value='Insert Data Set' onClick='self.location.href=\"%s&insert=yes\"'>&nbsp;&nbsp;&nbsp;\n", GetClearedURL());
+    }
+
     function PrintPage($html, $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs)
     {
@@ -404,7 +384,8 @@
         mysql_select_db($db);
 
-        $query0 = CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs);
+        $query0 = CreateQuery($alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs);
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
@@ -412,415 +393,352 @@
             if ($html=="1" || $html=="2")
             {
-                PrintMagicTable($result0, $alias, $rightalign, $limitsmean, $limitsmin, $limitsmax, "yes", $_GET);
-                foreach($_POST as $key => $val)
-                    if ($val=="On")
+                PrintMagicTable($result0, $alias, $rightalign, $limitsmean, $limitsmin, $limitsmax, $result1, "yes");
+
+                if ($_SESSION["sequon"]!=" " || $_SESSION["sequoff"]!=" ")
+                {
+                    printf("<div align='left'>\n");
+                    printf("Remark: To store your selection you have to press 'Update Data Set'<br> \n");
+                    if ($_SESSION["DisplaySelected"]!="yes" && ($_SESSION["sequon"]!=" " || $_SESSION["sequoff"]!=" "))
                     {
-                        if (ereg("ON$", $key))
-                            $sequon.=str_replace("ON", " ", $key);
-                        if (ereg("Off$", $key))
-                            $sequoff.=str_replace("Off", " ", $key);
+                        printf("Remark: To be able to remove sequence(s) from your selection you have to \n");
+                        printf("'Display Selected Sequences'");
+//                        printf("<input type='button' value='Display Selected Sequences' onClick='self.location.href=\"%s&DisplaySelected=yes\"'>\n", GetClearedURL("yes"));
+                        printf(" only.<br>\n");
                     }
-
-                printf("<input type='submit' value='Get Dataset'><br><br>\n");
-                printf("<input name='submit' type='hidden' value='post'>\n");
-
-                $on=str_replace(" ", ",", trim($sequon));
-                $off=str_replace(" ", ",", trim($sequoff));
-
-                $values=array("Sum(fRunTime)/60"         => $runtime,
-                              "Min(fRunTime)/60"         => $runtimemin,
-                              "Max(fUnsuitableInner)"    => $unsuitablemax,
-                              "Max(fUnreliableInner)"    => $unreliablemax,
-                              "Max(fIsolatedInner)"      => $isolatedmax,
-                              "Max(fIsolatedMaxCluster)" => $imcmax,
-                              "Max(fArrTimeMeanInner)"   => $arrtimemax,
-                              "Min(fArrTimeMeanInner)"   => $arrtimemin,
-                              "Max(fArrTimeRmsInner)"    => $arrtimermsmax,
-                              "Avg(fMeanPedRmsInner)"    => $pedrmsmean,
-                              "Std(fMeanPedRmsInner)"    => $pedrmsrms,
-                              "Min(fMeanPedRmsInner)"    => $pedrmsmin,
-                              "Max(fMeanPedRmsInner)"    => $pedrmsmax,
-                              "Min(fPulsePosMean)"       => $pulseposmin,
-                              "Max(fPulsePosMean)"       => $pulseposmax,
-                              "Max(fPulsePosRms)"        => $pulseposrmsmax,
-                              "Max(fMaxHumidity)"        => $hummax,
-                              "Max(fInhomogeneity)"      => $inhommax,
-                              "Avg(fInhomogeneity)"      => $inhommean,
-                              "Std(fInhomogeneity)"      => $inhomrms,
-                              "Min(fMeanNumberIslands)"  => $numislmin,
-                              "Max(fMeanNumberIslands)"  => $numislmax,
-                              "Min(fDataRate)"           => $clratemin,
-                              "Max(fDataRate)"           => $clratemax,
-                              "Min(fMuonRate)"           => $muonratemin,
-                              "Max(fMuonRate)"           => $muonratemax,
-                              "Min(fMuonNumber)"         => $muonnumbermin,
-                              "Avg(fPSF)"                => $psfmean,
-                              "Std(fPSF)"                => $psfrms,
-                              "Min(fPSF)"                => $psfmin,
-                              "Max(fPSF)"                => $psfmax,
-                              "Min(fEffOnTime/fRunTime)" => $relontimemin,
-                              "Max(fEffOnTime/fRunTime)" => $relontimemax,
-                              "Min(fBrightnessMed)"      => $brightmin,
-                              "Max(fBrightnessMed)"      => $brightmax,
-                              "Min(fNumStarsMed)"        => $idstarsmin,
-                              "Max(fNumStarsMed)"        => $idstarsmax,
-                              "Min(fNumStarsCorMed)"     => $corstarsmin,
-                              "Max(fNumStarsCorMed)"     => $corstarsmax,
-                              "Min(fZenithDistanceMin)"  => $zdmin,
-                              "Max(fZenithDistanceMax)"  => $zdmax,
-                              "Min(fRunStart)"           => $starttime,
-                              "Max(fRunStop)"            => $stoptime,
-                             );
-                //get runtimes of dataset
-                function GetSequenceValues($db_id, $sequences, $txt, &$values)
-                {
-                    $query="SELECT COUNT(*) ";
-                    foreach($values as $name => $varname)
-                        $query.=", " . $name;
-                    $query.=" FROM Sequences ";
-                    $query.=" LEFT JOIN Calibration USING(fSequenceFirst,fTelescopeNumber) ";
-                    $query.=" LEFT JOIN Star USING(fSequenceFirst,fTelescopeNumber) ";
-                    $query.=" WHERE Sequences.fSequenceFirst IN (" . $sequences . ")";
+                    printf("<br>\n");
+
+                    printf("<u>Your Data Set:</u> <br>\n");
+
+                    $on=str_replace(" ", ",", trim($_SESSION["sequon"]));
+                    $off=str_replace(" ", ",", trim($_SESSION["sequoff"]));
+
+                    $values=array("Sum(fRunTime)/60"         => $runtime,
+                                  "Min(fRunTime)/60"         => $runtimemin,
+                                  "Max(fUnsuitableInner)"    => $unsuitablemax,
+                                  "Max(fUnreliableInner)"    => $unreliablemax,
+                                  "Max(fIsolatedInner)"      => $isolatedmax,
+                                  "Max(fIsolatedMaxCluster)" => $imcmax,
+                                  "Max(fArrTimeMeanInner)"   => $arrtimemax,
+                                  "Min(fArrTimeMeanInner)"   => $arrtimemin,
+                                  "Max(fArrTimeRmsInner)"    => $arrtimermsmax,
+                                  "Avg(fMeanPedRmsInner)"    => $pedrmsmean,
+                                  "Std(fMeanPedRmsInner)"    => $pedrmsrms,
+                                  "Min(fMeanPedRmsInner)"    => $pedrmsmin,
+                                  "Max(fMeanPedRmsInner)"    => $pedrmsmax,
+                                  "Min(fPulsePosMean)"       => $pulseposmin,
+                                  "Max(fPulsePosMean)"       => $pulseposmax,
+                                  "Max(fPulsePosRms)"        => $pulseposrmsmax,
+                                  "Max(fMaxHumidity)"        => $hummax,
+                                  "Max(fInhomogeneity)"      => $inhommax,
+                                  "Avg(fInhomogeneity)"      => $inhommean,
+                                  "Std(fInhomogeneity)"      => $inhomrms,
+                                  "Min(fMeanNumberIslands)"  => $numislmin,
+                                  "Max(fMeanNumberIslands)"  => $numislmax,
+                                  "Avg(fDataRate)"           => $clratemean,
+                                  "Min(fDataRate)"           => $clratemin,
+                                  "Max(fDataRate)"           => $clratemax,
+                                  "Min(fMuonRate)"           => $muonratemin,
+                                  "Max(fMuonRate)"           => $muonratemax,
+                                  "Min(fMuonNumber)"         => $muonnumbermin,
+                                  "Avg(fPSF)"                => $psfmean,
+                                  "Std(fPSF)"                => $psfrms,
+                                  "Min(fPSF)"                => $psfmin,
+                                  "Max(fPSF)"                => $psfmax,
+                                  "Min(fEffOnTime/fRunTime)" => $relontimemin,
+                                  "Max(fEffOnTime/fRunTime)" => $relontimemax,
+                                  "Min(fBrightnessMed)"      => $brightmin,
+                                  "Max(fBrightnessMed)"      => $brightmax,
+                                  "Min(fNumStarsMed)"        => $idstarsmin,
+                                  "Max(fNumStarsMed)"        => $idstarsmax,
+                                  "Min(fNumStarsCorMed)"     => $corstarsmin,
+                                  "Max(fNumStarsCorMed)"     => $corstarsmax,
+                                  "Min(fZenithDistanceMin)"  => $zdmin,
+                                  "Max(fZenithDistanceMax)"  => $zdmax,
+                                  "Min(fRunStart)"           => $starttime,
+                                  "Max(fRunStop)"            => $stoptime,
+                                 );
+                    //get runtimes of dataset
+                    function GetSequenceValues($db_id, $sequences, $txt, &$values)
+                    {
+                        $query="SELECT COUNT(*) ";
+                        foreach($values as $name => $varname)
+                            $query.=", " . $name;
+                        $query.=" FROM Sequences ";
+                        $query.=" LEFT JOIN Calibration USING(fSequenceFirst,fTelescopeNumber) ";
+                        $query.=" LEFT JOIN Star USING(fSequenceFirst,fTelescopeNumber) ";
+                        $query.=" WHERE Sequences.fSequenceFirst IN (" . $sequences . ")";
+                        $result = mysql_query($query, $db_id);
+                        $row = mysql_fetch_assoc($result);
+                        foreach($values as $name => $varname)
+                            $values[$name][$txt]=$row[$name];
+                        mysql_free_result($result);
+                    }
+
+                    //get next dataset#
+                    $query="SELECT fDataSetNumber+1 FROM DataSets ORDER BY fDataSetNumber DESC LIMIT 0,1";
                     $result = mysql_query($query, $db_id);
                     $row = mysql_fetch_assoc($result);
-                    foreach($values as $name => $varname)
-                        $values[$name][$txt]=$row[$name];
+                    $dataset=$row["fDataSetNumber+1"];
+                    if (empty($dataset))
+                        $dataset=1;
                     mysql_free_result($result);
+
+                    //get sourcenames
+                    function GetSources($db_id, $sequences)
+                    {
+                        $query="SELECT fSourceName FROM Source LEFT JOIN Sequences USING(fSourceKEY) ";
+                        $query.="WHERE fSequenceFirst IN (" . $sequences . ") GROUP BY fSourceName";
+                        $result = mysql_query($query, $db_id);
+                        while ($row = mysql_fetch_assoc($result))
+                            $sources.=" " . $row["fSourceName"];
+                        mysql_free_result($result);
+                        return $sources;
+                    }
+                    $sourceson=GetSources($db_id, $on);
+                    $sourcesoff=GetSources($db_id, $off);
+
+                    //get sourcename for dataset
+                    $son=str_replace(" ", "','", trim($sourceson));
+                    $query="SELECT fRealSourceKEY, Count(*), fSourceName FROM Source where fSourceName IN ('" . $son . "') GROUP BY fRealSourceKEY";
+                    $result = mysql_query($query, $db_id);
+                    $row = mysql_fetch_assoc($result);
+                    $numsources=$row["Count(*)"];
+                    $numrealkeys=mysql_num_rows($result);
+                    $_SESSION["realsourcekey"]=$row["fRealSourceKEY"];
+                    $_SESSION["realsourcename"]=$row["fSourceName"];
+                    mysql_free_result($result);
+                    //printf("found %s sources with real sourcekey %s", $numsources, $realsourcekey);
+                    //printf("found %s keys", $numrealkeys);
+
+                    //check observationmode for on-sequences
+                    $query="SELECT fObservationModeKEY FROM Sequences where fSequenceFirst IN (" . $on . ") GROUP BY fObservationModeKEY";
+                    $result = mysql_query($query, $db_id);
+                    $row = mysql_fetch_assoc($result);
+                    $obskey=$row["fObservationModeKEY"];
+                    $numobskeys=mysql_num_rows($result);
+                    mysql_free_result($result);
+
+                    //check dt for on-sequences
+                    $query="SELECT fDiscriminatorThresholdTableKEY FROM Sequences where fSequenceFirst IN (" . $on . ") GROUP BY fDiscriminatorThresholdTableKEY";
+                    $result = mysql_query($query, $db_id);
+                    $numdtkeys=mysql_num_rows($result);
+                    mysql_free_result($result);
+
+
+                    //set limit
+                    $runtimelimit=5;
+                    $unsuitablemaxlimit=15;
+                    $isolatedlimit=0;
+                    $imclimit=0;
+                    $pedrmsrms=0.09;
+                    $scalelimit=1.3;
+                    $inhomlimit=13;
+                    $numstarslimit=20;
+                    $numstarscorlimit=10;
+
+
+                    //check values for infos, warnings and errors
+                    $numerr=0;
+                    if (!empty($on))
+                    {
+                        $color=array("INFO"  => "#000000",
+                                     "WARN"  => "#FF9900",
+                                     "ERROR" => "#FF0000");
+                        printf("<div align='left'><font><ul>\n");
+                        $vals=array("on", "off");
+                        foreach($vals as $num => $val)
+                        {
+                            if (empty(${$val}))
+                                continue;
+                            //get information from the database
+                            GetSequenceValues($db_id, ${$val}, $val, $values);
+
+                            if ($values["Min(fNumStarsCorMed)"][$val]<$numstarscorlimit)
+                                printf("<li style='color:%s'>%s: One of your %s-sequences has less than %s correlated stars (%s). </li>\n",
+                                       $color["WARN"], "WARN", $val, $numstarscorlimit, $values["Min(fNumStarsCorMed)"][$val]);
+                            if ($values["Min(fNumStarsMed)"][$val]<$numstarslimit)
+                                printf("<li style='color:%s'>%s: One of your %s-sequences has less than %s identified stars (%s). </li>\n",
+                                       $color["WARN"], "WARN", $val, $numstarslimit, $values["Min(fNumStarsMed)"][$val]);
+                            if ($values["Min(fRunTime)/60"][$val]<$runtimelimit)
+                                printf("<li style='color:%s'>%s: One of your %s-sequences is shorter than %s min (%s min). </li>\n",
+                                       $color["INFO"], "INFO", $val, $runtimelimit, $values["Min(fRunTime)/60"][$val]);
+                            if ($values["Max(fInhomogeneity)"][$val]>$inhomlimit)
+                                printf("<li style='color:%s'>%s: One of your %s-sequences has an inhomogeneity larger than %s (%s). </li>\n",
+                                       $color["WARN"], "WARN", $val, $inhomlimit, $values["Max(fInhomogeneity)"][$val]);
+                            if ($values["Max(fUnsuitableInner)"][$val]>$unsuitablemaxlimit)
+                                printf("<li style='color:%s'>%s: One of your %s-sequences has more than %s unsuitable inner pixel (%s). </li>\n",
+                                       $color["WARN"], "WARN", $val, $unsuitablemaxlimit, $values["Max(fUnsuitableInner)"][$val]);
+                            if ($values["Max(fIsolatedInner)"][$val]>$isolatedlimit)
+                            printf("<li style='color:%s'>%s: One of your %s-sequences has more than %s isolated inner pixel (%s). </li>\n",
+                                   $color["WARN"], "WARN", $val, $isolatedlimit, $values["Max(fIsolatedInner)"][$val]);
+                            if ($values["Max(fIsolatedMaxCluster)"][$val]>$imclimit)
+                                printf("<li style='color:%s'>%s: One of your %s-sequences has more than %s isolated max cluster (%s). </li>\n",
+                                       $color["WARN"], "WARN", $val, $imclimit, $values["Max(fIsolatedMaxCluster)"][$val]);
+                        }
+                        //check selected dataset for errors
+                        if (!empty($on) && $values["Max(fMeanPedRmsInner)"]["on"]>$values["Avg(fMeanPedRmsInner)"]["on"]+$pedrmsrms)
+                            printf("<li style='color:%s'>%s: One of your on-sequences has a PedRms larger than %s (%s).</li>\n",
+                                   $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("<li style='color:%s'>%s: One of your off-sequences has a PedRms larger than %s (%s). </li>\n",
+                                   $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("<li style='color:%s'>%s: One of your off-sequences has a PedRms smaller than %s (%s). </li>\n",
+                                   $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("<li style='color:%s'>%s: Your scale factor is larger than %s (%0.2f). Try to find more offdata! </li>\n",
+                                   $color["WARN"], "WARN", $scalelimit, $scale);
+                        $doubleseq=0;
+                        foreach(explode(" ", $_SESSION["sequon"]) as $n => $s)
+                        {
+                            if (ereg($s, $_SESSION["sequoff"]))
+                                $doubleseq++;
+                        }
+                        if ($obskey!=$_SESSION["obsmode"])
+                        {
+                            printf("<li style='color:%s'>%s: You have not selected any Off sequences. </li>\n",
+                                   $color["ERROR"], "ERROR", $doubleseq);
+                            $numerr=$numerr+1;
+                        }
+                        if ($doubleseq>0)
+                        {
+                            printf("<li style='color:%s'>%s: You have selected sequences (%s) as On AND Off. </li>\n",
+                                   $color["ERROR"], "ERROR", $doubleseq);
+                            $numerr=$numerr+1;
+                        }
+                        if ($numrealkeys>1)
+                        {
+                            printf("<li style='color:%s'>%s: You have selected more than one (%s) on source. </li>\n",
+                                   $color["ERROR"], "ERROR", $numrealkeys);
+                            $numerr=$numerr+1;
+                        }
+                        if ($numobskeys>1)
+                        {
+                            printf("<li style='color:%s'>%s: You have selected more than one (%s) different observation modes in your on sequences. </li>\n",
+                                   $color["ERROR"], "WARN", $numobskeys);
+                            //$numerr=$numerr+1;
+                        }     
+                        if ($numdtkeys>1)
+                        {
+                            printf("<li style='color:%s'>%s: Your selected on sequences have more than one (%s) different discriminator threshold tables. </li>\n",
+                                   $color["ERROR"], "WARN", $numdtkeys);
+                        }
+                        if (empty($_SESSION["realsourcekey"]))
+                        {
+                            printf("<li style='color:%s'>%s: The source you selected does not have a real sourcekey, yet. Please insert fRealSourceKEY in the DB for %s (contact: datacenter@astro.uni-wuerzburg.de). </li>\n",
+                                   $color["ERROR"], "ERROR", $sourceson);
+                            $numerr=$numerr+1;
+                        }
+                        if (empty($_SESSION["name"]))
+                        {
+                            printf("<li style='color:%s'>%s: You have to choose a name. </li>\n",
+                                   $color["ERROR"], "ERROR");
+                            $numerr=$numerr+1;
+                        }
+                        if (empty($_SESSION["comment"]))
+                        {
+                            printf("<li style='color:%s'>%s: You have to comment your data set. </li>\n",
+                                   $color["ERROR"], "ERROR");
+                            $numerr=$numerr+1;
+                        }
+                        printf("</ul></font>\n");
+                        printf("</div>");
+
+                        //set runtime in session (has to be after calling GetSequenceValues())
+                        $_SESSION["runtime"]  = $values["Sum(fRunTime)/60"]["on"];
+                        $_SESSION["zdmin"]    = $values["Min(fZenithDistanceMin)"]["on"];
+                        $_SESSION["zdmax"]    = $values["Max(fZenithDistanceMax)"]["on"];
+                        $_SESSION["meanrate"] = $values["Avg(fDataRate)"]["on"];
+                        $_SESSION["psfmean"]  = $values["Avg(fPSF)"]["on"];
+                        $_SESSION["psfmin"]   = $values["Min(fPSF)"]["on"];
+                        $_SESSION["psfmax"]   = $values["Max(fPSF)"]["on"];
+
+                        printf("SequencesOn: %s<br>\n", $_SESSION["sequon"]);
+                        if ($_SESSION["sequoff"]!=" ")
+                            printf("SequencesOff: %s<br>\n", $_SESSION["sequoff"]);
+
+                        //set observation mode
+                        if ($_SESSION["sequoff"]==" ")
+                            $obsmode="Wobble";
+                        else
+                            $obsmode="On";
+                        //get key from db for insert query
+                        $query   = "SELECT fObservationModeKEY FROM ObservationMode WHERE fObservationModeName='".$obsmode."'";
+                        $result  = mysql_query($query);
+                        $row = mysql_fetch_assoc($result);
+                        $_SESSION["obsmode"] = $row["fObservationModeKEY"];
+                        mysql_free_result($result);
+                        printf("Observation mode: %s <br>\n", $obsmode);
+                        printf("RunTime: %s min <br>\n", $_SESSION["runtime"]);
+                        printf("Mean Rate after cleaning: %s Hz <br>\n", $_SESSION["meanrate"]);
+                        printf("Zd: %s - %s deg <br>\n", $_SESSION["zdmin"], $_SESSION["zdmax"]);
+                        printf("PSF: %s (%s - %s) mm <br>\n", $_SESSION["psfmean"], $_SESSION["psfmin"], $_SESSION["psfmax"]);
+
+                        //user name
+                        printf("User name: %s <br><br>\n", $_SERVER['PHP_AUTH_USER']);
+
+                        // data set name and comment: to be inserted by the user
+                        printf("Data set name: &nbsp;<input name='name' type='text' size='20' maxlength='20' value='%s'><br>\n", $_SESSION["name"]);
+                        printf("Comment: &nbsp;<input name='comment' type='text' size='50' maxlength='255' value='%s'><br><br>\n", $_SESSION["comment"]);
+
+
+                        //PrintUpdateDataSetButton() has to be called before InsertDataSet()
+                        //   to ensure that there are no problem with insert and $_SESSION["insert"]
+
+                        //allow 'insert/get dataset' in case no error is found
+                        if ($numerr!=0)
+                        {
+                            printf("Remark: Only data sets without errors can be inserted.<br>");
+                            printf("<font color='red'>Your data set has %s error(s).</font><br><br>", $numerr);
+                            PrintUpdateDataSetButton();
+                        }
+                        else
+                        {
+                            PrintUpdateDataSetButton();
+
+                            if ($_SERVER['PHP_AUTH_USER']=="MAGIC")
+                                printf("<br><br>\n Remark: As user MAGIC you are not allowed to insert data sets into the database. For an own account, please contact datacenter@astro.uni-wuerzburg.de <br><br>\n");
+                            else
+                                InsertDataSet($values, $dataset);
+
+                            printf("<input type='button' value='Get Data Set File' onClick='self.location.href=\"%s&fSendTxt=2\"'>&nbsp;&nbsp;&nbsp;\n", GetClearedURL());
+                        }
+
+
+                        //print table with more information on dataset
+                        printf("<br><br><br>\n");
+                        printf("<table><tr><td colspan='2'><b>More Information on Your Data Set:<b></td></tr>");
+                        printf("<tr><td>Next DataSet# in DB: </td><td>%s</td></tr>", $dataset);
+                        printf("<tr><td valign='top'>SequencesOn:</td><td> %s</td></tr>", $_SESSION["sequon"]);
+                        if ($_SESSION["sequoff"]!=" ")
+                        {
+                            printf("<tr><td valign='top'>SequencesOff:</td><td> %s</td></tr>", $_SESSION["sequoff"]);
+                            printf("<tr><td>Scale factor (On/Off): </td><td>%0.2f</td></tr>", $scale);
+                        }
+                        printf("<tr><td>SourcenamesOn [%s]: </td><td>%s</td></tr>", str_word_count($sourceson, 0, "1234567890+"), $sourceson);
+                        if ($_SESSION["sequoff"]!=" ")
+                            printf("<tr><td>SourcenamesOff [%s]: </td><td>%s</td></tr>", str_word_count($sourcesoff, 0, "1234567890+"), $sourcesoff);
+                        printf("</table>\n");
+
+                        printf("<table border='1'>\n");
+                        printf("<tr><td>Value</td><td>On</td>");
+                        if (!empty($off))
+                            printf("<td>Off</td></tr>\n");
+                        foreach($values as $name => $varname)
+                        {
+                            printf("<tr><td>%s</td>\n", $name);
+                            foreach($vals as $num => $val)
+                                if (!empty(${$val}))
+                                    printf("<td>%s</td>\n", $varname[$val]);
+                            printf("</tr>\n");
+                        }
+                        printf("</table>\n");
+                    }
                 }
-
-                //get next dataset#
-                $query="SELECT fDataSetNumber+1 FROM DataSets ORDER BY fDataSetNumber DESC LIMIT 0,1";
-                $result = mysql_query($query, $db_id);
-                $row = mysql_fetch_assoc($result);
-                $dataset=$row["fDataSetNumber+1"];
-                if (empty($dataset))
-                    $dataset=1;
-                mysql_free_result($result);
-
-                //get sourcenames
-                function GetSources($db_id, $sequences)
-                {
-                    $query="SELECT fSourceName FROM Source LEFT JOIN Sequences USING(fSourceKEY) ";
-                    $query.="WHERE fSequenceFirst IN (" . $sequences . ") GROUP BY fSourceName";
-                    $result = mysql_query($query, $db_id);
-                    while ($row = mysql_fetch_assoc($result))
-                        $sources.=" " . $row["fSourceName"];
-                    mysql_free_result($result);
-                    return $sources;
-                }
-                $sourceson=GetSources($db_id, $on);
-                $sourcesoff=GetSources($db_id, $off);
-
-                //get sourcename for dataset
-                $son=str_replace(" ", "','", trim($sourceson));
-                $query="SELECT fRealSourceKEY, Count(*) FROM Source where fSourcename IN ('" . $son . "') GROUP BY fRealSourceKEY";
-//                printf("q: %s <br>", $query);
-                $result = mysql_query($query, $db_id);
-                $row = mysql_fetch_assoc($result);
-                $numsources=$row["Count(*)"];
-                $numrealkeys=mysql_num_rows($result);
-                $realsourcekey=$row["fRealSourceKEY"];
-                mysql_free_result($result);
-//                printf("found %s sources with real sourcekey %s", $numsources, $realsourcekey);
-//                printf("found %s keys", $numrealkeys);
-
-                //check observationmode for on-sequences
-                $query="SELECT fObservationModeKEY FROM Sequences where fSequenceFirst IN (" . $on . ") GROUP BY fObservationModeKEY";
-                $result = mysql_query($query, $db_id);
-                $numobskeys=mysql_num_rows($result);
-                mysql_free_result($result);
-
-                //check dt for on-sequences
-                $query="SELECT fDiscriminatorThresholdTableKEY FROM Sequences where fSequenceFirst IN (" . $on . ") GROUP BY fDiscriminatorThresholdTableKEY";
-                $result = mysql_query($query, $db_id);
-                $numdtkeys=mysql_num_rows($result);
-                mysql_free_result($result);
-
-
-                //set limit
-                $runtimelimit=5;
-                $unsuitablemaxlimit=15;
-                $isolatedlimit=0;
-                $imclimit=0;
-                $pedrmsrms=0.09;
-                $scalelimit=1.3;
-                $inhomlimit=13;
-                $numstarslimit=20;
-                $numstarscorlimit=10;
-
-
-                //check values for infos, warnings and errors
-                $numerr=0;
-                if (!empty($on))
-                {
-                    $color=array("INFO"  => "#000000",
-                                 "WARN"  => "#FF9900",
-                                 "ERROR" => "#FF0000");
-                    printf("<div align='left'><font><ul>\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("<li style='color:%s'>%s: one of your %s-sequences has less than %s correlated stars (%s)</li>",
-                                   $color["WARN"], "WARN", $val, $numstarscorlimit, $values["Min(fNumStarsCorMed)"][$val]);
-                        if ($values["Min(fNumStarsMed)"][$val]<$numstarslimit)
-                            printf("<li style='color:%s'>%s: one of your %s-sequences has less than %s identified stars (%s)</li>",
-                                   $color["WARN"], "WARN", $val, $numstarslimit, $values["Min(fNumStarsMed)"][$val]);
-                        if ($values["Min(fRunTime)/60"][$val]<$runtimelimit)
-                            printf("<li style='color:%s'>%s: one of your %s-sequences is shorter than %s min (%s min)</li>",
-                                   $color["INFO"], "INFO", $val, $runtimelimit, $values["Min(fRunTime)/60"][$val]);
-                        if ($values["Max(fInhomogeneity)"][$val]>$inhomlimit)
-                            printf("<li style='color:%s'>%s: one of your %s-sequences has an inhomogeneity larger than %s (%s)</li>",
-                                   $color["WARN"], "WARN", $val, $inhomlimit, $values["Max(fInhomogeneity)"][$val]);
-                        if ($values["Max(fUnsuitableInner)"][$val]>$unsuitablemaxlimit)
-                            printf("<li style='color:%s'>%s: one of your %s-sequences has more than %s unsuitable inner pixel (%s)</li>",
-                                   $color["WARN"], "WARN", $val, $unsuitablemaxlimit, $values["Max(fUnsuitableInner)"][$val]);
-                        if ($values["Max(fIsolatedInner)"][$val]>$isolatedlimit)
-                            printf("<li style='color:%s'>%s: one of your %s-sequences has more than %s isolated inner pixel (%s)</li>",
-                                   $color["WARN"], "WARN", $val, $isolatedlimit, $values["Max(fIsolatedInner)"][$val]);
-                        if ($values["Max(fIsolatedMaxCluster)"][$val]>$imclimit)
-                            printf("<li style='color:%s'>%s: one of your %s-sequences has more than %s isolated max cluster (%s)</li>",
-                                   $color["WARN"], "WARN", $val, $imclimit, $values["Max(fIsolatedMaxCluster)"][$val]);
-                    }
-                    if (!empty($on) && $values["Max(fMeanPedRmsInner)"]["on"]>$values["Avg(fMeanPedRmsInner)"]["on"]+$pedrmsrms)
-                        printf("<li style='color:%s'>%s: one of your on-sequences has a PedRms larger than %s (%s)</li>",
-                               $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("<li style='color:%s'>%s: one of your off-sequences has a PedRms larger than %s (%s)</li>",
-                               $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("<li style='color:%s'>%s: one of your off-sequences has a PedRms smaller than %s (%s)</li>",
-                               $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("<li style='color:%s'>%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("<li style='color:%s'>%s: You have selected more than one (%s) on source",
-                               $color["WARN"], "WARN", str_word_count($sourceson));
-                    */
-                    $doubleseq=0;
-//                    printf("finding: %s<br>", $sequon);
-                    foreach(explode(" ", $sequon) as $n => $s)
-                    {
-//                        printf("finding %s in %s <br>", $s, $sequoff);
-                        if (ereg($s, $sequoff))
-                        $doubleseq++;
-                    }
-                    if ($doubleseq>0)
-                    {
-                        printf("<li style='color:%s'>%s: You have selected sequences (%s) as On AND Off",
-                               $color["ERROR"], "ERROR", $doubleseq);
-                        $numerr=$numerr+1;
-                    }
-                    if ($numrealkeys>1)
-                    {
-                        printf("<li style='color:%s'>%s: You have selected more than one (%s) on source",
-                               $color["ERROR"], "ERROR", $numrealkeys);
-                        $numerr=$numerr+1;
-                    }
-                    if ($numobskeys>1)
-                    {
-                        printf("<li style='color:%s'>%s: You have selected more than one (%s) different observation modes for your on sequences",
-                               $color["ERROR"], "WARN", $numobskeys);
-//                        $numerr=$numerr+1;
-                    }
-                    if ($numdtkeys>1)
-                    {
-                        printf("<li style='color:%s'>%s: Your selected on sequences have more than one (%s) different discriminator threshold tables ",
-                               $color["ERROR"], "WARN", $numdtkeys);
-                    }
-                    if (empty($_POST["fObservationModeKEY"]) && !empty($_GET["obsmode"]))
-                        $_POST["fObservationModeKEY"]=$_GET["obsmode"];
-                    if ($_POST["fObservationModeKEY"]==3 && empty($off))
-                    {
-                        printf("<li style='color:%s'>%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("<li style='color:%s'>%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("<li style='color:%s'>%s: You have to choose an observation mode.",
-                               $color["ERROR"], "ERROR");
-                        $numerr=$numerr+1;
-                    }
-                    if (empty($_POST["fUserKEY"]))
-                    {
-                        printf("<li style='color:%s'>%s: You have to choose your username.",
-                               $color["ERROR"], "ERROR");
-                        $numerr=$numerr+1;
-                    }
-                    if (empty($_POST["name"]))
-                    {
-                        printf("<li style='color:%s'>%s: You have to choose a name.",
-                               $color["ERROR"], "ERROR");
-                        $numerr=$numerr+1;
-                    }
-                    if (empty($_POST["comment"]))
-                    {
-                        printf("<li style='color:%s'>%s: You have to comment your dataset.",
-                               $color["ERROR"], "ERROR");
-                        $numerr=$numerr+1;
-                    }
-                    //                printf("<li></li>");
-                    printf("</ul></font>\n");
-
-                    printf("<div align='left'>");
-                    printf("SequencesOn: %s<br>", $sequon);
-                    printf("SequencesOff: %s<br>", $sequoff);
-                    $insquery[0]="INSERT DataSets SET fDataSetNumber=" . $dataset . ", fUserKEY=" . $_POST["fUserKEY"];
-                    $insquery[0].=", fComment='" . $_POST["comment"] . "', fObservationModeKEY=" . $_POST["fObservationModeKEY"];
-                    $insquery[0].=", fDataSetName='" . $_POST["name"] . "', fSourceKEY= " . $realsourcekey;
-                    $insquery[0].=", fRunStart='" . $values["Min(fRunStart)"]["on"];
-                    $insquery[0].="', fRunStop='" . $values["Max(fRunStop)"]["on"];
-                    $insquery[0].="', fZenithDistanceMin=" . $values["Min(fZenithDistanceMin)"]["on"];
-                    $insquery[0].=", fZenithDistanceMax=" . $values["Max(fZenithDistanceMax)"]["on"];
-                    $insquery[0].=", fRunTime=" . $values["Sum(fRunTime)/60"]["on"];
-                    $insquery[1]="INSERT DataSetProcessStatus SET fDataSetNumber=" . $dataset . ", fDataSetInserted=Now()";
-                    $i=2;
-                    foreach(explode(" ", trim($sequon)) as $key => $sequ)
-                    {
-                        $insquery[$i]="INSERT DataSetSequenceMapping SET fDataSetNumber=" . $dataset;
-                        $insquery[$i].=", fSequenceFirst=" . $sequ . ", fOnOff=1";
-                        $i=$i+1;
-                    }
-                    if (!empty($off))
-                    {
-                        foreach(explode(" ", trim($sequoff)) as $key => $sequ)
-                        {
-                            $insquery[$i]="INSERT DataSetSequenceMapping SET fDataSetNumber=" . $dataset;
-                            $insquery[$i].=", fSequenceFirst=" . $sequ . ", fOnOff=2";
-                            $i=$i+1;
-                        }
-                    }
-                    foreach($insquery as $num => $q)
-                    {
-                        if (!empty($_POST["insert"]) && $numerr==0)
-                        {
-                            printf("Inserted Query #%s: %s<br>", $num, $q);
-                            $insresult=mysql_query($q);
-                            if (mysql_errno()>0)
-                                printf("&nbsp; Errorno: %s <br>", mysql_errno());
-                            if (mysql_error()!="")
-                                printf("&nbsp; Errormsg: %s <br>", mysql_error());
-                            if (mysql_info()!="")
-                                printf("&nbsp; Info: %s <br>", mysql_info());
-                            printf("&nbsp; Affected Rows: %s <br>", mysql_affected_rows());
-                            mysql_free_result($insresult);
-                            if (mysql_errno()>0)
-                            {
-                                printf("ERROR => stop inserting");
-                                break;
-                            }
-                        }
-                    }
-                    printf("</div>");
-                    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: &nbsp;<input name='name' type='text' size='20' maxlength='20' value='%s'><br>\n", $_POST["name"]);
-                    printf("Comment: &nbsp;<input name='comment' type='text' size='50' maxlength='255' value='%s'><br>\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&nbsp;<select name='fObservationModeKEY' size='1' class='Width'>\n");
-                    while ($row = mysql_fetch_row($result))
-                    {
-                        if (!empty($_POST["fObservationModeKEY"]) && $_POST["fObservationModeKEY"]==$row[0])
-                            printf("<option value='%s' selected>%s</option>\n", $row[0], $row[1]);
-                        else
-                            printf("<option value='%s'>%s</option>\n", $row[0], $row[1]);
-                    }
-                    printf("</select><br>\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&nbsp;<select name='fUserKEY' size='1' class='Width'>\n");
-                    while ($row = mysql_fetch_row($result))
-                    {
-                        if (!empty($_POST["fUserKEY"]) && $_POST["fUserKEY"]==$row[0])
-                            printf("<option value='%s' selected>%s</option>\n", $row[0], $row[1]);
-                        else
-                            printf("<option value='%s'>%s</option>\n", $row[0], $row[1]);
-                    }
-                    printf("</select><br>\n");
-                    mysql_free_result($result);
-
-                    if ($numerr!=0)
-                    {
-                        printf("Remark: only datasets without errors can be inserted.<br>");
-                        printf("Your dataset has %s error(s).<br>", $numerr);
-                    }
-                    printf("<input type='checkbox' name='insert' value='On'>insert\n");
-
-                    printf("<table><tr><td colspan='2' align='center'>Dataset</td></tr>");
-                    printf("<tr><td>proposed DataSet#: </td><td>%s</td></tr>", $dataset);
-                    printf("<tr><td valign='top'>SequencesOn:</td><td> %s</td></tr>", $sequon);
-                    if (!empty($sequoff))
-                        printf("<tr><td valign='top'>SequencesOff:</td><td> %s</td></tr>", $sequoff);
-                    printf("<tr><td>Scale: </td><td>%0.2f</td></tr>", $scale);
-                    printf("<tr><td>SourcenamesOn[%s]: </td><td>%s</td></tr>", str_word_count($sourceson), $sourceson);
-                    printf("<tr><td>SourcenamesOff[%s]: </td><td>%s</td></tr>", str_word_count($sourcesoff), $sourcesoff);
-                    printf("</table>\n");
-
-                    printf("<table border='1'>\n");
-                    printf("<tr><td>Value</td><td>On</td>");
-                    if (!empty($off))
-                        printf("<td>Off</td></tr>\n");
-                    foreach($values as $name => $varname)
-                    {
-                        printf("<tr><td>%s</td>\n", $name);
-                        foreach($vals as $num => $val)
-                            if (!empty(${$val}))
-                                printf("<td>%s</td>\n", $varname[$val]);
-                        printf("</tr>\n");
-                    }
-                    printf("</table>\n");
-                }
+                else
+                    printf("<input type='submit' value='Get Data Set'><br><br>\n");
 
                 printf("</div>\n");
-                /*
-                printf("<table border='1'><tr>\n");
-                printf("<td>--</td>\n");
-                foreach($values as $name => $varname)
-                        printf("<td>%s</td>\n", $name);
-                $vals=array("on", "off");
-                foreach($vals as $num => $val)
-                {
-                    GetSequenceValues($db_id, ${$val}, $val, $values);
-                    printf("</tr><tr>\n");
-                    printf("<td>On</td>\n");
-                    foreach($values as $name => $varname)
-                        printf("<td>%s</td>\n", $varname[$val]);
-                }
-                printf("</tr></table>\n");
-                */
-
-                printf("</center>\n");
                 printf("</td>\n");
                 printf("</tr>\n");
@@ -832,4 +750,5 @@
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
@@ -843,37 +762,127 @@
     include ("magicdefs.php");
 
+//    $debug="yes";
+    session_start();
+    if ($debug)
+    {
+        echo "GET: ";
+        print_r($_GET);
+        echo " <br>";
+
+        echo "POST: ";
+        print_r($_POST);
+        echo " <br>";
+    }
+
+    // set values given by $_GET
+    foreach ($_GET as $element => $value)
+        $_SESSION[$element]=$value;
+
+    // unset values in case of 'Reset'
+    if (empty($_GET))
+        foreach($_SESSION as $element => $value)
+            unset($_SESSION[$element]);
+
+    // set values given by $_POST
+    if (!empty($_POST))
+        foreach ($_POST as $element => $value)
+            $_SESSION[$element]=$value;
+
+
+
+    if ($debug)
+        print_r($_SESSION);
+
+    // remove sequence from selection
+    if (!empty($_POST) && $_SESSION["DisplaySelected"]=="yes" && $_SESSION["DisplaySelectedOld"]=="yes")
+        foreach ($_SESSION as $key => $element)
+            if (($_SESSION[$key]=="On") //value is set
+                && (ereg("^[0-9]*ON$", $key) || ereg("^[0-9]*Off$", $key)) // it is a sequence number
+                && (!$_POST[$key]==On)) // the sequence is not given in $_POST any more
+                unset($_SESSION[$key]);
+
+    //store old value of $_SESSION["DisplaySelected"]
+    if ($_SESSION["DisplaySelected"]=="yes")
+    {
+        unset($_SESSION["fNumStart"]);
+        $_GET["fNumStart"]=0;
+        $_SESSION["DisplaySelectedOld"]="yes";
+    }
+    else
+        $_SESSION["DisplaySelectedOld"]="no";
+
+    $_SESSION["sequon"]=" ";
+    $_SESSION["sequoff"]=" ";
+    foreach($_SESSION as $key => $val)
+        if ($val=="On")
+        {
+            if (ereg("^[0-9]*ON$", $key))
+                $_SESSION["sequon"].=str_replace("ON", " ", $key);
+            if (ereg("^[0-9]*Off$", $key))
+                $_SESSION["sequoff"].=str_replace("Off", " ", $key);
+        }
+    if ($_SESSION["sequon"]==" " && $_SESSION["sequoff"]==" ")
+    {
+        $_SESSION["DisplaySelected"]="no";
+        $_SESSION["DisplaySelectedOld"]="no";
+    }
+
     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)
+    if (!isset($_SERVER['PHP_AUTH_USER']))
     {
         header('WWW-Authenticate: Basic realm="Build Datasets"');
         header('HTTP/1.0 401 Unauthorized');
-        echo 'Cancelled.';
         return;
     }
     else
     {
-//    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
-//    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
-//    printf("pw: %s", crypt($_SERVER['PHP_AUTH_PW']));
-
-        if (crypt($_SERVER['PHP_AUTH_PW'], $sitepw)!=$sitepw || $_SERVER['PHP_AUTH_USER']!=$siteuser)
-        {
-            printf("<br>pw or user incorrect<br>");
+        $db_id = mysql_connect($host, $user, $pw);
+        if ($db_id==FALSE)
+        {
+            printf("mysql_connect returned the following error:<br>");
+            printf("%s<br>", mysql_error());
+            die("");
+        }
+
+        $userquery   = "SELECT fUserName, fPassword, fUserKEY FROM " . $db . ".User ORDER BY fUserKEY";
+        $userresult  = mysql_query($userquery);
+        if (!$userresult)
+            echo "query failed";
+        $validuser="no";
+        while ($userrow = mysql_fetch_assoc($userresult))
+        {
+//            echo crypt($_SERVER['PHP_AUTH_PW']). "<br>";
+            if (crypt($_SERVER['PHP_AUTH_PW'], $userrow["fPassword"])==$userrow["fPassword"]
+                && $_SERVER['PHP_AUTH_USER']==$userrow["fUserName"])
+            {
+                $validuser="yes";
+                $_SESSION["user"]=$userrow["fUserKEY"];
+            }
+        }
+        mysql_free_result($userresult);
+        if ($validuser=="no")
+        {
+            printf("<br>Password or username incorrect<br>");
             return;
         }
     }
 
-    if (!empty($_GET["fSendTxt"]))
-    {
-        header("Content-type: application/octet");
-        header("Content-Disposition: attachment; filename=query-result.txt");
-
-        PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs);
+    if (!empty($_SESSION["fSendTxt"]))
+    {
+        header("Content-Type: application/octet");
+        switch($_SESSION["fSendTxt"])
+        {
+        case 1:
+            header("Content-Disposition: attachment; filename=query-result.txt");
+            PrintPage("0", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs);
+            break;
+        case 2:
+            header("Content-Disposition: attachment; filename=dataset_".str_replace(" ", "_", $_SESSION["name"]).".txt");
+            PrintDataSetFile();
+            echo "hallo\n";
+        }
+        unset($_SESSION["fSendTxt"]);
     }
     else
@@ -883,7 +892,9 @@
         $environment = sizeof($_GET);
 
-        InitGet($_GET);
-        if (empty($_GET["fPrintTable"]))
-            PrintForm($_GET, $host, $user, $pw, $db, $limitsmean, $limitsmin, $limitsmax, $alias);
+        // Find out whether it is the first call to the php script
+        $first = empty($_GET["fRunMin"]) && empty($_GET["fRunMax"]);
+        InitBuildDataSets($first);
+        if (empty($_SESSION["fPrintTable"]))
+            PrintForm($host, $user, $pw, $db, $limitsmean, $limitsmin, $limitsmax, $alias);
 
         if ($environment==0)
@@ -891,5 +902,5 @@
         else
         {
-            if (empty($_GET["fPrintTable"]))
+            if (empty($_SESSION["fPrintTable"]))
                 PrintPage("1", $host, $user, $pw, $db, $alias, $rightalign, $checkwhere, $checkgroup, $checkstatusgroup, $limitsmean, $limitsmin, $limitsmax, $needs);
             else
@@ -902,4 +913,4 @@
     ini_set("display_errors", "Off");
     ini_set("mysql.trace_mode", "Off");
-}
+
 ?>
Index: trunk/MagicSoft/Mars/datacenter/db/ctadefs.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/ctadefs.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/ctadefs.php	(revision 9498)
@@ -25,10 +25,10 @@
 $checkwhere = array
     (
-     "fParticleTypeName"                 => CheckWhere("fParticleTypeKEY",                 $_GET),
+     "fParticleTypeName"  => CheckWhere("fParticleTypeKEY"),
     );
 
 $checkgroup = array
     (
-     "fParticleTypeName"                 => CheckGroup("fParticleTypeKEY",                 $_GET),
+     "fParticleTypeName"  => CheckGroup("fParticleTypeKEY"),
     );
 
@@ -36,10 +36,10 @@
 $checkstatusgroup = array
     (
-     "fCorsikaSimTelarray" => CheckStatusGroup("fCorsikaSimTelarrayStatus", $_GET),
-     "fChimp"              => CheckStatusGroup("fChimpStatus",              $_GET),
-     "fCTAStar"            => CheckStatusGroup("fCTAStarStatus",            $_GET),
-     "fStereoB"            => CheckStatusGroup("fStereoBStatus",            $_GET),
-     "fStereoC"            => CheckStatusGroup("fStereoCStatus",            $_GET),
-     "fStereoG"            => CheckStatusGroup("fStereoGStatus",            $_GET),
+     "fCorsikaSimTelarray" => CheckStatusGroup("fCorsikaSimTelarrayStatus"),
+     "fChimp"              => CheckStatusGroup("fChimpStatus"),
+     "fCTAStar"            => CheckStatusGroup("fCTAStarStatus"),
+     "fStereoB"            => CheckStatusGroup("fStereoBStatus"),
+     "fStereoC"            => CheckStatusGroup("fStereoCStatus"),
+     "fStereoG"            => CheckStatusGroup("fStereoGStatus"),
     );
 
Index: trunk/MagicSoft/Mars/datacenter/db/ctamcinfo.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/ctamcinfo.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/ctamcinfo.php	(revision 9498)
@@ -1,5 +1,5 @@
 <?php
 {
-    function CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs, $timelimits)
+    function CreateQuery($alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs, $timelimits)
     {
         $fromtable="MCRunData";
@@ -15,5 +15,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0 || $statusgroups>0)
@@ -204,13 +204,15 @@
 
         if (empty($_GET["fNumStart"]))
-            $_GET["fNumStart"]=0;
+            $start=0;
+        else
+            $start=$_GET["fNumStart"];
 
         if (empty($_GET["fSendTxt"]))
-            $query0 .= " LIMIT " . $_GET["fNumStart"] . ", " . $_GET["fNumResults"];
+            $query0 .= " LIMIT " . $start . ", " . $_GET["fNumResults"];
 
         return $query0;
     }
 
-    function InitGet($_GET)
+    function InitGet()
     {
         // Find out whether it is the first call to the php script
@@ -220,5 +222,5 @@
     }
 
-    function PrintForm($_GET, $host, $user, $pw, $db)
+    function PrintForm($host, $user, $pw, $db)
     {
         printf("<center>\n");
@@ -279,16 +281,18 @@
         mysql_query("SET BIG_TABLES=1"); // necessary for mySQL <= 4
 
-        $query0 = CreateQuery($_GET, $alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs, $timelimits);
+        $query0 = CreateQuery($alias, $checkwhere, $checkgroup, $checkstatusgroup, $needs, $timelimits);
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1" || $html=="2")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
@@ -298,5 +302,5 @@
 
     include ("include.php");
-    include ("db.php");
+    include ("db2.php");
     include ("menu.php");
     include ("ctadefs.php");
@@ -319,7 +323,7 @@
         $environment = sizeof($_GET);
 
-        InitGet($_GET);
+        InitGet();
         if (empty($_GET["fPrintTable"]))
-            PrintForm($_GET, $host, $user, $pw, $db);
+            PrintForm($host, $user, $pw, $db);
 
         if ($environment==0)
Index: trunk/MagicSoft/Mars/datacenter/db/culminating.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/culminating.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/culminating.php	(revision 9498)
@@ -10,5 +10,5 @@
                 $groups++;
 
-        $query0  = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0)
@@ -223,13 +223,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/datacheck.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/datacheck.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/datacheck.php	(revision 9498)
@@ -20,5 +20,5 @@
                 $enumgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0)
@@ -416,13 +416,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1" || $html=="2")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/datasetinfo-aio.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/datasetinfo-aio.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/datasetinfo-aio.php	(revision 9498)
@@ -15,5 +15,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0 || $statusgroups>0)
@@ -232,13 +232,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1" || $html=="2")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/datasetinfo.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/datasetinfo.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/datasetinfo.php	(revision 9498)
@@ -15,5 +15,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0)
@@ -372,13 +372,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1" || $html=="2")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/dbstatus.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/dbstatus.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/dbstatus.php	(revision 9498)
@@ -51,5 +51,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0)
@@ -355,13 +355,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1" || $html=="2")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/findoffdata.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/findoffdata.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/findoffdata.php	(revision 9498)
@@ -15,5 +15,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0)
@@ -409,13 +409,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1" || $html=="2")
-                PrintMagicTable($result0, $alias, $rightalign, $limitsmean, $limitsmin, $limitsmax, "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, $limitsmean, $limitsmin, $limitsmax, $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/include.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/include.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/include.php	(revision 9498)
@@ -255,9 +255,7 @@
 }
 
+//for download of output
 function PrintText($result0)
 {
-//    header("Content-type: application/octet");
-//    header("Content-Disposition: attachment; filename=query-result.txt");
-
     while ($row0 = mysql_fetch_assoc($result0))
     {
@@ -293,20 +291,7 @@
 }
 
-function Checkbox2($val, $set, $text)
-{
-    $value=$val.$set;
-    switch ($set)
-    {
-    case  "ON":
-        if (!isset($_POST["submit"]) && ereg(" ".$val." ", $_GET["Set"]))
-            $_POST[$value]="On";
-        break;
-    case "Off":
-        if (!isset($_POST["submit"]) && ereg(" ".$val." ", $_GET["Set2"]))
-            $_POST[$value]="On";
-        break;
-    }
-
-    if ($_POST[$value]=="On")
+function Checkbox2($value, $text)
+{
+    if ($_SESSION[$value]=="On")
         $checked = "checked";
     else
@@ -316,5 +301,5 @@
 }
 
-function CheckWhere($column, $_GET)
+function CheckWhere($column)
 {
     foreach ($_GET as $key => $element)
@@ -330,5 +315,5 @@
 }
 
-function CheckGroup($column, $_GET)
+function CheckGroup($column)
 {
     foreach ($_GET as $key => $element)
@@ -344,5 +329,5 @@
 }
 
-function CheckStatusGroup($column, $_GET)
+function CheckStatusGroup($column)
 {
     foreach ($_GET as $key => $element)
@@ -353,5 +338,5 @@
 }
 
-function CheckEnumGroup($column, $_GET)
+function CheckEnumGroup($column)
 {
     foreach ($_GET as $key => $element)
@@ -360,60 +345,4 @@
                 return -1;
     return 0;
-}
-
-function CreateMenu($rows)
-{
-    $menu = "";
-
-    if (empty($_GET["fNumResults"]))
-        return;
-
-    if ($_GET["fNumStart"]!=0)
-    {
-        $uri = htmlspecialchars($_SERVER["REQUEST_URI"]);
-        $pos = strpos($uri, "fNumStart");
-        $amp3=FALSE;
-        if ($pos!=FALSE)
-        {
-            $amp1 = substr($uri, 0, $pos-1);
-            $amp2 = substr($uri, $pos);
-            $amp3 = strchr($amp2, "&");
-
-            $uri = $amp1;
-        }
-        $pos = $_GET["fNumStart"]-$rows;
-        if ($pos<0)
-            $pos=0;
-        $uri .= "&fNumStart=" . $pos;
-        if ($amp3!=FALSE)
-            $uri .= $amp3;
-
-        $menu .= "<A HREF='" . $uri . "'><<< Prev</A>\n";
-    }
-
-    $menu .= "&nbsp;&nbsp;&nbsp;---&nbsp;<B>";
-    $menu .= $_GET["fNumStart"];
-    $menu .= "</B>&nbsp;---&nbsp;&nbsp;&nbsp;\n";
-
-    if ($rows==$_GET["fNumResults"])
-    {
-        $uri = $_SERVER["REQUEST_URI"];
-        $pos = strpos($uri, "fNumStart");
-        $amp3=FALSE;
-        if ($pos!=FALSE)
-        {
-            $amp1 = substr($uri, 0, $pos-1);
-            $amp2 = substr($uri, $pos);
-            $amp3 = strchr($amp2, "&");
-
-            $uri = $amp1;
-        }
-        $uri .= "&fNumStart=" . ($_GET["fNumStart"]+$rows);
-        if ($amp3!=FALSE)
-            $uri .= $amp3;
-
-        $menu .= "<A HREF='" . htmlspecialchars($uri) . "'>Next >>></A>\n";
-    }
-    return $menu;
 }
 
@@ -455,5 +384,136 @@
 }
 
-function PrintMagicTable($result0, $alias, $rightalign, $limitsmean, $limitsmin, $limitsmax, $form, $_GET)
+//function for button in builddatasets.php
+function GetClearedURL($all)
+{
+//    $url=htmlspecialchars($_SERVER["REQUEST_URI"]);
+    $url=$_SERVER["REQUEST_URI"];
+//    echo "before:".$url."<br>";
+    if ($all=="yes")
+    {
+//        echo "replace <br>";
+//        $url=str_replace("&DisplaySelected", "halo", $url);
+        $url=str_replace("&DisplaySelected=yes", "", $url);
+        $url=str_replace("&DisplaySelected=no", "", $url);
+    }
+    $url=str_replace("&insert=yes", "", $url);
+    $url=str_replace("&fSendTxt=2", "", $url);
+    $url=str_replace("&fSendTxt=1", "", $url);
+//    echo "after:".$url."<br>";
+    $url=htmlspecialchars($url);
+    return $url;
+}
+
+function PrintUpdateDataSetButton()
+{
+    if (empty($_SESSION["insert"]))
+        printf("<input type='submit' value='Update Data Set'>&nbsp;&nbsp;&nbsp;\n");
+    else
+        printf("<input type='button' value='Continue' onClick='self.location.href=\"%s\"'>&nbsp;&nbsp;&nbsp;\n", GetClearedURL());
+
+}
+
+//function for button in builddatasets.php
+function PrintDisplaySequencesButtons()
+{
+    if ($_SESSION["DisplaySelected"]!="yes" && ($_SESSION["sequon"]!=" " || $_SESSION["sequoff"]!=" "))
+    {
+        PrintUpdateDataSetButton();
+        printf("<input type='button' value='Display Selected Sequences' onClick='self.location.href=\"%s&DisplaySelected=yes\"'><br><br>\n", GetClearedURL("yes"));
+    }
+
+    if ($_SESSION["DisplaySelected"]=="yes")
+    {
+        PrintUpdateDataSetButton();
+        printf("<input type='button' value='Display All Sequences' onClick='self.location.href=\"%s&DisplaySelected=no\"'>\n", GetClearedURL("yes"));
+        printf("&nbsp;&nbsp;&nbsp;<i>Currently only selected sequences are displayed.</i><br><br>\n");
+    }
+}
+
+
+function ReplaceInUri($name, $rows, $direction, $result1=0)
+{
+    $uri = htmlspecialchars($_SERVER["REQUEST_URI"]);
+    $pos = strpos($uri, "fNumStart");
+    $amp3=FALSE;
+    if ($pos!=FALSE)
+    {
+        $amp1 = substr($uri, 0, $pos-1);
+        $amp2 = substr($uri, $pos);
+        $amp3 = strchr($amp2, "&");
+
+        $uri = $amp1;
+    }
+
+    switch($direction)
+    {
+    case 0:
+        $pos = $_GET["fNumStart"]-$rows;
+        if ($pos<0)
+            $pos=0;
+        break;
+    case 1:
+        $pos = $_GET["fNumStart"]+$rows;
+        break;
+    case 2:
+        $pos = 0;
+        break;
+    case 3:
+        $row1 = mysql_fetch_assoc($result1);
+        $pos = $row1["FOUND_ROWS()"]-$rows+1;
+        break;
+    }
+
+    $uri .= "&fNumStart=" . $pos;
+    if ($amp3!=FALSE)
+        $uri .= $amp3;
+
+    switch($direction)
+    {
+    case 0:
+        $link .= " <A HREF='" . $uri . "'>< Prev</A> \n";
+        break;
+    case 1:
+        $link .= " <A HREF='" . $uri . "'>Next ></A> \n";
+        break;
+    case 2:
+        $link .= " <A HREF='" . $uri . "'><< First</A> \n";
+        break;
+    case 3:
+        $link .= " <A HREF='" . $uri . "'>Last >></A> \n";
+        break;
+    }
+    return $link;
+}
+
+function CreateMenu($rows, $result1)
+{
+    $menu = "";
+
+    if (empty($_GET["fNumResults"]))
+        return;
+
+    if ($_GET["fNumStart"]!=0)
+    {
+        $menu .= ReplaceInUri("fNumStart", $rows, 2);
+        $menu .= ReplaceInUri("fNumStart", $rows, 0);
+    }
+
+    $menu .= "&nbsp;&nbsp;&nbsp;---&nbsp;<B>";
+    if (empty($_GET["fNumStart"]))
+        $menu .= "0";
+    else
+        $menu .= $_GET["fNumStart"];
+    $menu .= "</B>&nbsp;---&nbsp;&nbsp;&nbsp;\n";
+
+    if ($rows==$_GET["fNumResults"])
+    {
+        $menu .= ReplaceInUri("fNumStart", $rows, 1);
+        $menu .= ReplaceInUri("fNumStart", $rows, 3, $result1);
+    }
+    return $menu;
+}
+
+function PrintMagicTable($result0, $alias, $rightalign, $limitsmean, $limitsmin, $limitsmax, $result1, $form="")
 {
     $col   = FALSE;
@@ -470,11 +530,15 @@
 
 
-    $menu = CreateMenu(mysql_num_rows($result0));
-
+    $menu = CreateMenu(mysql_num_rows($result0), $result1);
+
+    if ($form)
+    {
+        printf("<form method='POST'>");
+        PrintDisplaySequencesButtons();
+    }
     printf("\n<center>\n");
-    if ($form)
-        printf("<form method='POST'>");
     if (empty($_GET["fPrintTable"]))
         printf("%s\n", $menu);
+
     printf("<table BORDER='0' style='margin-top:1ex'>\n");
     $counter=0;
@@ -518,6 +582,6 @@
         if ($form)
         {
-            CheckBox2($row0["Sequ"], "ON","");
-            CheckBox2($row0["Sequ"], "Off","");
+            CheckBox2($row0["Sequ"]."ON","");
+            CheckBox2($row0["Sequ"]."Off","");
         }
         foreach ($row0 as $key => $element)
@@ -607,15 +671,18 @@
      */
 
-    printf("<P><B>Number of displayed results: %d</B><P><P>\n", mysql_num_rows($result0));
+    $row1 = mysql_fetch_assoc($result1);
+    printf("<P><B>Number of displayed results: %d of %s in total</B><P><P>\n", mysql_num_rows($result0), $row1["FOUND_ROWS()"]);
     if (empty($_GET["fPrintTable"]))
         printf("%s\n", $menu);
     printf("<P>\n");
+    printf("</center>\n");
 
     if (!$form)
     {
-        printf("</center>\n");
         printf("</td>\n");
         printf("</tr>\n");
     }
+    else
+        PrintDisplaySequencesButtons();
 }
 
Index: trunk/MagicSoft/Mars/datacenter/db/index.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/index.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/index.php	(revision 9498)
@@ -10,5 +10,5 @@
                 $groups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0)
@@ -372,13 +372,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/magicdefs.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/magicdefs.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/magicdefs.php	(revision 9498)
@@ -66,64 +66,64 @@
 $checkwhere = array
     (
-     "fRunTypeName"                      => CheckWhere("fRunTypeKEY",                      $_GET),
-     "fProjectName"                      => CheckWhere("fProjectKEY",                      $_GET),
-     "fSourceName"                       => CheckWhere("fSourceKEY",                       $_GET),
-     "fMagicNumberName"                  => CheckWhere("fMagicNumberKEY",                  $_GET),
-     "fL1TriggerTableName"               => CheckWhere("fL1TriggerTableKEY",               $_GET),
-     "fL2TriggerTableName"               => CheckWhere("fL2TriggerTableKEY",               $_GET),
-     "fL3TriggerTableName"               => CheckWhere("fL3TriggerTableKEY",               $_GET),
-     "fHvSettingsName"                   => CheckWhere("fHvSettingsKEY",                   $_GET),
-     "fCalibrationScriptName"            => CheckWhere("fCalibrationScriptKEY",            $_GET),
-     "fExcludedFDAName"                  => CheckWhere("fExcludedFDAKEY",                  $_GET),
-     "fManuallyChangedName"              => CheckWhere("fManuallyChangedKEY",              $_GET),
-     "fObservationModeName"              => CheckWhere("fObservationModeKEY",              $_GET),
-     "fSumTriggerFlagName"               => CheckWhere("fSumTriggerFlagKEY",               $_GET),
-     "fDiscriminatorThresholdTableName"  => CheckWhere("fDiscriminatorThresholdTableKEY",  $_GET),
-     "fTriggerDelayTableName"            => CheckWhere("fTriggerDelayTableKEY",            $_GET),
-     "fTestFlagName"                     => CheckWhere("fTestFlagKEY",                     $_GET),
-     "fLightConditionsName"              => CheckWhere("fLightConditionsKEY",              $_GET),
-     "fParticleTypeName"                 => CheckWhere("fParticleTypeKEY",                 $_GET),
-     "fFitsFileName"                     => CheckWhere("fFitsFileKEY",                     $_GET),
-     "fObjectName"                       => CheckWhere("fObjectKEY",                       $_GET),
-     "fStatusName"                       => CheckWhere("fStatusKEY",                       $_GET),
-     "fTelescopeName"                    => CheckWhere("fTelescopeKEY",                    $_GET),
-     "fBandName"                         => CheckWhere("fBandKEY",                         $_GET),
-     "fUserName"                         => CheckWhere("fUserKEY",                         $_GET),
-     "fCycleName"                        => CheckWhere("fCycleKEY",                        $_GET),
-     "fPIName"                           => CheckWhere("fPIKEY",                           $_GET),
-     "fWorkingGroupName"                 => CheckWhere("fWorkingGroupKEY",                 $_GET),
-     "fProposalName"                     => CheckWhere("fProposalKEY",                     $_GET),
+     "fRunTypeName"                      => CheckWhere("fRunTypeKEY"),
+     "fProjectName"                      => CheckWhere("fProjectKEY"),
+     "fSourceName"                       => CheckWhere("fSourceKEY"),
+     "fMagicNumberName"                  => CheckWhere("fMagicNumberKEY"),
+     "fL1TriggerTableName"               => CheckWhere("fL1TriggerTableKEY"),
+     "fL2TriggerTableName"               => CheckWhere("fL2TriggerTableKEY"),
+     "fL3TriggerTableName"               => CheckWhere("fL3TriggerTableKEY"),
+     "fHvSettingsName"                   => CheckWhere("fHvSettingsKEY"),
+     "fCalibrationScriptName"            => CheckWhere("fCalibrationScriptKEY"),
+     "fExcludedFDAName"                  => CheckWhere("fExcludedFDAKEY"),
+     "fManuallyChangedName"              => CheckWhere("fManuallyChangedKEY"),
+     "fObservationModeName"              => CheckWhere("fObservationModeKEY"),
+     "fSumTriggerFlagName"               => CheckWhere("fSumTriggerFlagKEY"),
+     "fDiscriminatorThresholdTableName"  => CheckWhere("fDiscriminatorThresholdTableKEY"),
+     "fTriggerDelayTableName"            => CheckWhere("fTriggerDelayTableKEY"),
+     "fTestFlagName"                     => CheckWhere("fTestFlagKEY"),
+     "fLightConditionsName"              => CheckWhere("fLightConditionsKEY"),
+     "fParticleTypeName"                 => CheckWhere("fParticleTypeKEY"),
+     "fFitsFileName"                     => CheckWhere("fFitsFileKEY"),
+     "fObjectName"                       => CheckWhere("fObjectKEY"),
+     "fStatusName"                       => CheckWhere("fStatusKEY"),
+     "fTelescopeName"                    => CheckWhere("fTelescopeKEY"),
+     "fBandName"                         => CheckWhere("fBandKEY"),
+     "fUserName"                         => CheckWhere("fUserKEY"),
+     "fCycleName"                        => CheckWhere("fCycleKEY"),
+     "fPIName"                           => CheckWhere("fPIKEY"),
+     "fWorkingGroupName"                 => CheckWhere("fWorkingGroupKEY"),
+     "fProposalName"                     => CheckWhere("fProposalKEY"),
     );
 
 $checkgroup = array
     (
-     "fRunTypeName"                      => CheckGroup("fRunTypeKEY",                      $_GET),
-     "fProjectName"                      => CheckGroup("fProjectKEY",                      $_GET),
-     "fSourceName"                       => CheckGroup("fSourceKEY",                       $_GET),
-     "fMagicNumberName"                  => CheckGroup("fMagicNumberKEY",                  $_GET),
-     "fL1TriggerTableName"               => CheckGroup("fL1TriggerTableKEY",               $_GET),
-     "fL2TriggerTableName"               => CheckGroup("fL2TriggerTableKEY",               $_GET),
-     "fL3TriggerTableName"               => CheckGroup("fL3TriggerTableKEY",               $_GET),
-     "fHvSettingsName"                   => CheckGroup("fHvSettingsKEY",                   $_GET),
-     "fCalibrationScriptName"            => CheckGroup("fCalibrationScriptKEY",            $_GET),
-     "fExcludedFDAName"                  => CheckGroup("fExcludedFDAKEY",                  $_GET),
-     "fManuallyChangedName"              => CheckGroup("fManuallyChangedKEY",              $_GET),
-     "fObservationModeName"              => CheckGroup("fObservationModeKEY",              $_GET),
-     "fSumTriggerFlagName"               => CheckGroup("fSumTriggerFlagKEY",              $_GET),
-     "fDiscriminatorThresholdTableName"  => CheckGroup("fDiscriminatorThresholdTableKEY",  $_GET),
-     "fTriggerDelayTableName"            => CheckGroup("fTriggerDelayTableKEY",            $_GET),
-     "fTestFlagName"                     => CheckGroup("fTestFlagKEY",                     $_GET),
-     "fLightConditionsName"              => CheckGroup("fLightConditionsKEY",              $_GET),
-     "fParticleTypeName"                 => CheckGroup("fParticleTypeKEY",                 $_GET),
-     "fFitsFileName"                     => CheckGroup("fFitsFileKEY",                     $_GET),
-     "fObjectName"                       => CheckGroup("fObjectKEY",                       $_GET),
-     "fStatusName"                       => CheckGroup("fStatusKEY",                       $_GET),
-     "fBandName"                         => CheckGroup("fBandKEY",                         $_GET),
-     "fUserName"                         => CheckGroup("fUserKEY",                         $_GET),
-     "fTelescopeName"                    => CheckGroup("fTelescopeKEY",                    $_GET),
-     "fCycleName"                        => CheckWhere("fCycleKEY",                        $_GET),
-     "fPIName"                           => CheckWhere("fPIKEY",                           $_GET),
-     "fWorkingGroupName"                 => CheckWhere("fWorkingGroupKEY",                 $_GET),
-     "fProposalName"                     => CheckWhere("fProposalKEY",                     $_GET),
+     "fRunTypeName"                      => CheckGroup("fRunTypeKEY"),
+     "fProjectName"                      => CheckGroup("fProjectKEY"),
+     "fSourceName"                       => CheckGroup("fSourceKEY"),
+     "fMagicNumberName"                  => CheckGroup("fMagicNumberKEY"),
+     "fL1TriggerTableName"               => CheckGroup("fL1TriggerTableKEY"),
+     "fL2TriggerTableName"               => CheckGroup("fL2TriggerTableKEY"),
+     "fL3TriggerTableName"               => CheckGroup("fL3TriggerTableKEY"),
+     "fHvSettingsName"                   => CheckGroup("fHvSettingsKEY"),
+     "fCalibrationScriptName"            => CheckGroup("fCalibrationScriptKEY"),
+     "fExcludedFDAName"                  => CheckGroup("fExcludedFDAKEY"),
+     "fManuallyChangedName"              => CheckGroup("fManuallyChangedKEY"),
+     "fObservationModeName"              => CheckGroup("fObservationModeKEY"),
+     "fSumTriggerFlagName"               => CheckGroup("fSumTriggerFlagKEY"),
+     "fDiscriminatorThresholdTableName"  => CheckGroup("fDiscriminatorThresholdTableKEY"),
+     "fTriggerDelayTableName"            => CheckGroup("fTriggerDelayTableKEY"),
+     "fTestFlagName"                     => CheckGroup("fTestFlagKEY"),
+     "fLightConditionsName"              => CheckGroup("fLightConditionsKEY"),
+     "fParticleTypeName"                 => CheckGroup("fParticleTypeKEY"),
+     "fFitsFileName"                     => CheckGroup("fFitsFileKEY"),
+     "fObjectName"                       => CheckGroup("fObjectKEY"),
+     "fStatusName"                       => CheckGroup("fStatusKEY"),
+     "fBandName"                         => CheckGroup("fBandKEY"),
+     "fUserName"                         => CheckGroup("fUserKEY"),
+     "fTelescopeName"                    => CheckGroup("fTelescopeKEY"),
+     "fCycleName"                        => CheckWhere("fCycleKEY"),
+     "fPIName"                           => CheckWhere("fPIKEY"),
+     "fWorkingGroupName"                 => CheckWhere("fWorkingGroupKEY"),
+     "fProposalName"                     => CheckWhere("fProposalKEY"),
     );
 
@@ -131,25 +131,25 @@
 $checkstatusgroup = array
     (
-     "fCCFilled"                         => CheckStatusGroup("fCCFilledStatus",            $_GET),
-     "fExclusionsDone"                   => CheckStatusGroup("fExclusionsDoneStatus",      $_GET),
-     "fSequenceEntriesBuilt"             => CheckStatusGroup("fSequenceEntriesBuiltStatus",$_GET),
-     "fCCFileAvail"                      => CheckStatusGroup("fCCFileAvailStatus",         $_GET),
-     "fCaCoFileAvail"                    => CheckStatusGroup("fCaCoFileAvailStatus",       $_GET),
-     "fCaCoFileFound"                    => CheckStatusGroup("fCaCoFileFoundStatus",       $_GET),
-     "fRawFileAvail"                     => CheckStatusGroup("fRawFileAvailStatus",        $_GET),
-     "fTimingCorrection"                 => CheckStatusGroup("fTimingCorrectionStatus",    $_GET),
-     "fDataCheckDone"                    => CheckStatusGroup("fDataCheckDoneStatus",       $_GET),
-//     "fFillDotRaw"                       => CheckStatusGroup("fFillDotRawStatus",          $_GET),
-     "fSequenceFileWritten"              => CheckStatusGroup("fSequenceFileWrittenStatus", $_GET),
-     "fAllFilesAvail"                    => CheckStatusGroup("fAllFilesAvailStatus",       $_GET),
-     "fCallisto"                         => CheckStatusGroup("fCallistoStatus",            $_GET),
-     "fFillCallisto"                     => CheckStatusGroup("fFillCallistoStatus",        $_GET),
-     "fStar"                             => CheckStatusGroup("fStarStatus",                $_GET),
-     "fFillStar"                         => CheckStatusGroup("fFillStarStatus",            $_GET),
-     "fDataSetInserted"                  => CheckStatusGroup("fDataSetInsertedStatus",     $_GET),
-     "fDataSetFileWritten"               => CheckStatusGroup("fDataSetFileWrittenStatus",  $_GET),
-     "fStarFilesAvail"                   => CheckStatusGroup("fStarFilesAvailStatus",      $_GET),
-     "fGanymed"                          => CheckStatusGroup("fGanymedStatus",             $_GET),
-     "fFillGanymed"                      => CheckStatusGroup("fFillGanymedStatus",         $_GET),
+     "fCCFilled"                         => CheckStatusGroup("fCCFilledStatus"),
+     "fExclusionsDone"                   => CheckStatusGroup("fExclusionsDoneStatus"),
+     "fSequenceEntriesBuilt"             => CheckStatusGroup("fSequenceEntriesBuiltStatus"),
+     "fCCFileAvail"                      => CheckStatusGroup("fCCFileAvailStatus"),
+     "fCaCoFileAvail"                    => CheckStatusGroup("fCaCoFileAvailStatus"),
+     "fCaCoFileFound"                    => CheckStatusGroup("fCaCoFileFoundStatus"),
+     "fRawFileAvail"                     => CheckStatusGroup("fRawFileAvailStatus"),
+     "fTimingCorrection"                 => CheckStatusGroup("fTimingCorrectionStatus"),
+     "fDataCheckDone"                    => CheckStatusGroup("fDataCheckDoneStatus"),
+//     "fFillDotRaw"                       => CheckStatusGroup("fFillDotRawStatus"),
+     "fSequenceFileWritten"              => CheckStatusGroup("fSequenceFileWrittenStatus"),
+     "fAllFilesAvail"                    => CheckStatusGroup("fAllFilesAvailStatus"),
+     "fCallisto"                         => CheckStatusGroup("fCallistoStatus"),
+     "fFillCallisto"                     => CheckStatusGroup("fFillCallistoStatus"),
+     "fStar"                             => CheckStatusGroup("fStarStatus"),
+     "fFillStar"                         => CheckStatusGroup("fFillStarStatus"),
+     "fDataSetInserted"                  => CheckStatusGroup("fDataSetInsertedStatus"),
+     "fDataSetFileWritten"               => CheckStatusGroup("fDataSetFileWrittenStatus"),
+     "fStarFilesAvail"                   => CheckStatusGroup("fStarFilesAvailStatus"),
+     "fGanymed"                          => CheckStatusGroup("fGanymedStatus"),
+     "fFillGanymed"                      => CheckStatusGroup("fFillGanymedStatus"),
     );
 
@@ -157,8 +157,8 @@
 $checkenumgroup = array
     (
-     "fHasSignal"              => CheckEnumGroup("fHasSignalEnum",             $_GET),
-     "fHasPedestal"            => CheckEnumGroup("fHasPedestalEnum",           $_GET),
-     "fHasSignalInterlaced"    => CheckEnumGroup("fHasSignalInterlacedEnum",   $_GET),
-     "fHasPedestalInterlaced"  => CheckEnumGroup("fHasPedestalInterlacedEnum", $_GET),
+     "fHasSignal"              => CheckEnumGroup("fHasSignalEnum"),
+     "fHasPedestal"            => CheckEnumGroup("fHasPedestalEnum"),
+     "fHasSignalInterlaced"    => CheckEnumGroup("fHasSignalInterlacedEnum"),
+     "fHasPedestalInterlaced"  => CheckEnumGroup("fHasPedestalInterlacedEnum"),
     );
 
Index: trunk/MagicSoft/Mars/datacenter/db/mcdefs.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/mcdefs.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/mcdefs.php	(revision 9498)
@@ -17,12 +17,12 @@
 $checkwhere = array
     (
-     "fParticleTypeName"                 => CheckWhere("fParticleTypeKEY",                 $_GET),
-     "fAtmosphericModelName"             => CheckWhere("fAtmosphericModelKEY",             $_GET),
+     "fParticleTypeName"                 => CheckWhere("fParticleTypeKEY"),
+     "fAtmosphericModelName"             => CheckWhere("fAtmosphericModelKEY"),
     );
 
 $checkgroup = array
     (
-     "fParticleTypeName"                 => CheckGroup("fParticleTypeKEY",                 $_GET),
-     "fAtmosphericModelName"             => CheckGroup("fAtmosphericModelKEY",             $_GET),
+     "fParticleTypeName"                 => CheckGroup("fParticleTypeKEY"),
+     "fAtmosphericModelName"             => CheckGroup("fAtmosphericModelKEY"),
     );
 
@@ -30,6 +30,6 @@
 $checkstatusgroup = array
     (
-     "fCorsikaInputCreated" => CheckStatusGroup("fCorsikaInputCreatedStatus", $_GET),
-     "fCorsikaFileAvail" => CheckStatusGroup("fCorsikaFileAvailStatus", $_GET),
+     "fCorsikaInputCreated" => CheckStatusGroup("fCorsikaInputCreatedStatus"),
+     "fCorsikaFileAvail" => CheckStatusGroup("fCorsikaFileAvailStatus"),
     );
 
Index: trunk/MagicSoft/Mars/datacenter/db/mcinfo.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/mcinfo.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/mcinfo.php	(revision 9498)
@@ -15,5 +15,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0 || $statusgroups>0)
@@ -279,13 +279,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1" || $html=="2")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/menu.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/menu.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/menu.php	(revision 9498)
@@ -698,6 +698,6 @@
         $starmax = $_GET["fStarStop"];
 
-    printf("<p>StarDone&nbsp;(yyyy-mm-dd)&nbsp;from&nbsp;<input name=\"fStarStart\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"%s\">\n", $starmin);
-    printf("to&nbsp;<input name=\"fStarStop\" type=\"text\" size=\"10\" maxlength=\"10\" value=\"%s\">&nbsp;&nbsp;&nbsp;&nbsp;\n", $starmax);
+    printf("<p>StarDone&nbsp;(yyyy-mm-dd hh:mm:ss)&nbsp;from&nbsp;<input name=\"fStarStart\" type=\"text\" size=\"19\" maxlength=\"19\" value=\"%s\">\n", $starmin);
+    printf("to&nbsp;<input name=\"fStarStop\" type=\"text\" size=\"19\" maxlength=\"19\" value=\"%s\">&nbsp;&nbsp;&nbsp;&nbsp;\n", $starmax);
 }
 
@@ -766,5 +766,5 @@
 }
 
-function InitFailInfo($_GET, $first)
+function InitFailInfo($first)
 {
     if (empty($_GET["fStartTime"]))
@@ -781,5 +781,5 @@
 }
 
-function InitInfo($_GET, $first)
+function InitInfo($first)
 {
     if (empty($_GET["fNumResults"]))
@@ -838,8 +838,8 @@
 
     if (empty($_GET["fProposalName"]))
-        $_GET["fPropsalName"]="Off";
-}
-
-function InitRunStatus($_GET, $first)
+        $_GET["fProposalName"]="Off";
+}
+
+function InitRunStatus($first)
 {
    if (empty($_GET["fDataCheckDone"]))
@@ -880,9 +880,9 @@
 }
 
-function InitRunInfo($_GET, $first)
-{
-    InitRunStatus($_GET, $first);
-    InitInfo($_GET, $first);
-    InitFailInfo($_GET, $first);
+function InitRunInfo($first)
+{
+    InitRunStatus($first);
+    InitInfo($first);
+    InitFailInfo($first);
 
     if (empty($_GET["fLinks"]))
@@ -950,5 +950,5 @@
 }
 
-function InitSequStatus($_GET, $first)
+function InitSequStatus($first)
 {
     if (empty($_GET["fSequenceFileWritten"]))
@@ -989,5 +989,5 @@
 }
 
-function InitStarInfo($_GET, $first)
+function InitStarInfo($first)
 {
     if (empty($_GET["fMeanNumberIslands"]))
@@ -1061,5 +1061,5 @@
 }
 
-function InitCalInfo($_GET, $first)
+function InitCalInfo($first)
 {
     if (empty($_GET["fUnreliableInner"]))
@@ -1157,11 +1157,11 @@
 }
 
-function InitSequInfo($_GET, $first)
-{
-    InitInfo($_GET, $first);
-    InitSequStatus($_GET, $first);
-    InitFailInfo($_GET, $first);
-    InitCalInfo($_GET, $first);
-    InitStarInfo($_GET, $first);
+function InitSequInfo($first)
+{
+    InitInfo($first);
+    InitSequStatus($first);
+    InitFailInfo($first);
+    InitCalInfo($first);
+    InitStarInfo($first);
 
     if (empty($_GET["fRunTime/60"]))
@@ -1189,9 +1189,12 @@
         $_GET["fSumTriggerFlagName"]="Off";
 
+    if (empty($_GET["fOnlySum"]))
+        $_GET["fOnlySum"]="Off";
+
 //    if (empty($_GET["fManuallyChangedName"]))
 //        $_GET["fManuallyChangedName"]="Off";
 }
 
-function InitDataSetStatus($_GET, $first)
+function InitDataSetStatus($first)
 {
     if (empty($_GET["fDataSetInserted"]))
@@ -1226,8 +1229,8 @@
 }
 
-function InitDataSetInfo($_GET, $first)
-{
-    InitDataSetStatus($_GET, $first);
-    InitFailInfo($_GET, $first);
+function InitDataSetInfo($first)
+{
+    InitDataSetStatus($first);
+    InitFailInfo($first);
 
     if (empty($_GET["fNumResults"]))
@@ -1299,7 +1302,7 @@
 }
 
-function InitFindOffData($_GET, $first)
-{
-    InitSequInfo($_GET, $first);
+function InitFindOffData($first)
+{
+    InitSequInfo($first);
 
     //init for limits
@@ -1441,5 +1444,92 @@
 }
 
-function InitCTAMCRunStatus($_GET, $first)
+function InitBuildDataSets($first)
+{
+        if (empty($_GET["fNumResults"]))
+//            $_GET["fNumResults"]="50";
+            $_GET["fNumResults"]="10";
+
+        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["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["fAvgCloudiness"]))
+            $_GET["fAvgCloudiness"]=$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($first);
+}
+
+function InitCTAMCRunStatus($first)
 {
     if (empty($_GET["fCorsikaSimTelarray"]))
@@ -1481,12 +1571,12 @@
 }
 
-function InitCTAMCRunInfo($_GET, $first)
+function InitCTAMCRunInfo($first)
 {
     if (empty($_GET["fNumResults"]))
         $_GET["fNumResults"]="50";
 
-    InitCTAMCRunStatus($_GET, $first);
-    InitInfo($_GET, $first);
-    InitFailInfo($_GET, $first);
+    InitCTAMCRunStatus($first);
+    InitInfo($first);
+    InitFailInfo($first);
 
     if (empty($_GET["fNumEvents"]))
Index: trunk/MagicSoft/Mars/datacenter/db/opticaldata.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/opticaldata.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/opticaldata.php	(revision 9498)
@@ -10,5 +10,5 @@
                 $groups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0)
@@ -247,13 +247,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/printtable.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/printtable.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/printtable.php	(revision 9498)
@@ -28,5 +28,5 @@
 
         $fromtable=$_GET["fTable"];
-        $query0  = "SELECT * FROM " . $fromtable;
+        $query0  = "SELECT SQL_CALC_FOUND_ROWS * FROM " . $fromtable;
         if (!empty($_GET["fSortBy"]))
         {
@@ -39,4 +39,5 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
@@ -50,5 +51,5 @@
                 (
                 );
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             }
             else
@@ -56,4 +57,5 @@
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/querycal.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/querycal.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/querycal.php	(revision 9498)
@@ -3,5 +3,5 @@
     function CreateQuery($_GET, $alias, $checkwhere)
     {
-        $query0 = "SELECT fSequenceFirst as 'Sequence#' ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS fSequenceFirst as 'Sequence#' ";
 
         foreach ($_GET as $key => $element)
@@ -217,13 +217,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/querymc.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/querymc.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/querymc.php	(revision 9498)
@@ -10,5 +10,5 @@
                 $groups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0)
@@ -239,13 +239,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/queryrbk.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/queryrbk.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/queryrbk.php	(revision 9498)
@@ -50,5 +50,5 @@
         mysql_select_db($db);
 
-        $query0  = "SELECT fRunBookDate AS Date, fRunBookText AS Entry ";
+        $query0  = "SELECT SQL_CALC_FOUND_ROWS fRunBookDate AS Date, fRunBookText AS Entry ";
         $query0 .= "FROM " . $db . ".RunBook ";
         $query0 .= "WHERE fRunBookDate REGEXP '^" . $_GET["fDate"] . "' ";
@@ -63,4 +63,5 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
@@ -76,5 +77,5 @@
                 (
                 );
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             }
             else
@@ -82,4 +83,5 @@
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/queryseq.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/queryseq.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/queryseq.php	(revision 9498)
@@ -10,5 +10,5 @@
                 $groups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0)
@@ -314,13 +314,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/querystar.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/querystar.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/querystar.php	(revision 9498)
@@ -3,5 +3,5 @@
     function CreateQuery($_GET, $alias, $checkwhere)
     {
-        $query0 = "SELECT fSequenceFirst as 'Sequence#' ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS fSequenceFirst as 'Sequence#' ";
 
         foreach ($_GET as $key => $element)
@@ -160,13 +160,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/runinfo-aio.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/runinfo-aio.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/runinfo-aio.php	(revision 9498)
@@ -15,5 +15,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0 || ((!empty($_GET["fGroupByDate"])) && !$_GET["fGroupByDate"]==0) || $statusgroups>0)
@@ -324,13 +324,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1" || $html=="2")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/runinfo.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/runinfo.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/runinfo.php	(revision 9498)
@@ -15,5 +15,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0)
@@ -515,13 +515,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1" || $html=="2")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/sequinfo-aio.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/sequinfo-aio.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/sequinfo-aio.php	(revision 9498)
@@ -15,5 +15,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0 || ((!empty($_GET["fGroupByDate"])) && !$_GET["fGroupByDate"]==0) || $statusgroups>0)
@@ -397,13 +397,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1" || $html=="2")
-                PrintMagicTable($result0, $alias, $rightalign, $limitsmean, $limitsmin, $limitsmax, "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, $limitsmean, $limitsmin, $limitsmax, $result1, "");
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/sequinfo.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/sequinfo.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/sequinfo.php	(revision 9498)
@@ -15,5 +15,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($groups>0)
@@ -628,13 +628,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1" || $html=="2")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/sources.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/sources.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/sources.php	(revision 9498)
@@ -4,5 +4,5 @@
     {
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
         if ($_GET["fLinks"]=="Off" || !empty($_GET["fSendTxt"]))
             $query0 .= " fSourceName as 'Source' ";
@@ -112,13 +112,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/statusrps.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/statusrps.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/statusrps.php	(revision 9498)
@@ -3,5 +3,5 @@
     function CreateQuery($_GET, $alias, $checkstatusgroup, $checkwhere, $needs)
     {
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         $statusgroups = 0;
@@ -203,13 +203,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/statussbs.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/statussbs.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/statussbs.php	(revision 9498)
@@ -8,5 +8,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($statusgroups>0)
@@ -179,13 +179,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
Index: trunk/MagicSoft/Mars/datacenter/db/statussps.php
===================================================================
--- trunk/MagicSoft/Mars/datacenter/db/statussps.php	(revision 9493)
+++ trunk/MagicSoft/Mars/datacenter/db/statussps.php	(revision 9498)
@@ -8,5 +8,5 @@
                 $statusgroups++;
 
-        $query0 = "SELECT ";
+        $query0 = "SELECT SQL_CALC_FOUND_ROWS ";
 
         if ($statusgroups>0)
@@ -192,13 +192,15 @@
 
         $result0 = mysql_query($query0, $db_id);
+        $result1 = mysql_query("SELECT FOUND_ROWS()", $db_id);
 
         if ($result0)
         {
             if ($html=="1")
-                PrintMagicTable($result0, $alias, $rightalign, "", "", "", "", $_GET);
+                PrintMagicTable($result0, $alias, $rightalign, "", "", "", $result1);
             else
                 PrintText($result0);
 
             mysql_free_result($result0);
+            mysql_free_result($result1);
         }
         mysql_close($db_id);
