<?php
/*
function PrintTable($table)
{
    $db_id = mysql_connect("hercules.astro.uni-wuerzburg.de", "MAGIC", "d99swMT!");
    if ($db_id==FALSE)
    {
            printf("mysql_connect returned the following error:<br>");
            printf("%s<br>", mysql_error());
            die("");
    }
    printf("%s<br>", $table);
    printf("<table BORDER=\"1\">");

    $query = "EXPLAIN ";
    $query .= $table;
    
    $result = mysql_query($query);
    $numrows = mysql_num_rows($result);
    $numcols = mysql_num_fields($result);
    printf("%d x %d<br>", $numrows, $numcols);

    printf("<tr>");
    for ($i=0; $i<$numrows; $i++)
    {
       $row = mysql_fetch_row($result);
       printf("<th>%s</th> ", $row[0]);
    }
    printf("</tr>");
    
    $query = "SELECT * FROM ";
    $query .= $table;
    
    $result = mysql_query($query);
    
    $numrows = mysql_num_rows($result);
    $numcols = mysql_num_fields($result);
    printf("%d x %d<br>", $numrows, $numcols);

    while ($row = mysql_fetch_row($result))
    {
       printf("<tr>");
       foreach ($row as $entry)
       {
     	   printf("<td>%s</td> ", $entry);
       }
       printf("</tr>");
    }
    printf("</table>");
    
    mysql_free_result($result);

    mysql_close($db_id);
}
*/

function EnumQuery($name)
{
    $var  = $name . "Enum";
    $txt  = "";
    switch ($_GET[$var])
    {
    case 0: $txt .= ""; break;
    case 1: $txt .= $name . "='yes' AND "; break;
    case 2: $txt .= $name . "='no' AND "; break;
    case 3: $txt .= ""; break;
    }
    return $txt;
}

function PrintEnumMenu($name, $text)
{
    $var = $name . "Enum";

    if ($_GET[$name]=="On")
        $checked = "checked";
    else
        $checked = "";

    printf("    <input type=\"checkbox\" name=\"%s\" value=\"On\" %s>%s\n", $name, $checked, $text);
    printf("<BR>");

    printf(" <select name=\"%s\">\n", $var);

    $status = array
        ( 0 => "all",
          1 => "yes",
          2 => "no",
          3 => "group by"
        );

    $stat=$_GET[$var];
    for ($i=0; $i<4; $i++)
    {
        if ($stat==$i)
            printf("<option value=\"%d\" selected>%s</option>\n", $i, $status[$i]);
        else
            printf("<option value=\"%d\">%s</option>\n", $i, $status[$i]);
    }

    printf(" </select>\n");
    printf(" &nbsp;&nbsp;&nbsp;\n");

}

function StatusQuery($name)
{
    $var  = $name . "Status";
    $txt  = "";
    switch ($_GET[$var])
    {
    case 0: $txt .= ""; break;
    case 1: $txt .= "NOT (IsNull(" . $name . ") OR " . $name . "='1970-01-01 00:00:00') AND "; break;
    case 2: $txt .= "IsNull(" . $name . ") AND "; break;
    case 3: $txt .= $name ."='1970-01-01 00:00:00' AND "; break;
    case 4: $txt .= ""; break;
    }
    return $txt;
}

function PrintStatusMenu($name, $text)
{
    $var = $name . "Status";

    if ($_GET[$name]=="On")
        $checked = "checked";
    else
        $checked = "";

    printf("    <input type=\"checkbox\" name=\"%s\" value=\"On\" %s>%s\n", $name, $checked, $text);
    printf("<BR>");

    printf(" <select name=\"%s\">\n", $var);

    $status = array
        ( 0 => "all",
          1 => "done",
          2 => "not done",
          3 => "not to be done",
          4 => "group by"
        );

    $stat=$_GET[$var];
    for ($i=0; $i<5; $i++)
    {
        if ($stat==$i)
            printf("<option value=\"%d\" selected>%s</option>\n", $i, $status[$i]);
        else
            printf("<option value=\"%d\">%s</option>\n", $i, $status[$i]);
    }

    /*
    $status = array("all", "done", "not done", "not to be done");
    $counter = 0;
    foreach ($status as $element)
    {
        if ($counter==$_GET[$var])
            printf("<option value=\"%d\" selected>%3s</option>\n", $counter++, $element);
        else
            printf("<option value=\"%d\">%3s</option>\n", $counter++, $element);
    }*/
    printf(" </select>\n");
    printf(" &nbsp;&nbsp;&nbsp;\n");

}

function PrintLimitsMenu($limits, $rms, $alias)
{
    foreach($limits as $key => $element)
    {
        printf("<tr><td>%s</td>\n", $alias[$key]);
        $mean=$key . "Mean";
        $limitmean=$_GET[$mean];
        printf("<td><input name=\"%sMean\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\"></td>\n", $key, $limitmean);
        if ($rms[$key]=="yes")
        {
            $rms2=$key . "Rms";
            $limitrms=$_GET[$rms2];
            printf("<td><input name=\"%sRms\" type=\"text\" size=\"6\" maxlength=\"6\" value=\"%s\"></td>\n", $key, $limitrms);
        }
        else
            printf("<td><br></td>\n");
        printf("</tr>\n");
    }

}

function PrintPullDown($db, $table, $name, $index, $descr)
{
    $db_id = mysql_connect("hercules.astro.uni-wuerzburg.de", "MAGIC", "d99swMT!");
    if ($db_id==FALSE)
    {
            printf("mysql_connect returned the following error:<br>");
            printf("%s<br>", mysql_error());
            die("");
    }

    $query   = "SELECT " . $index . ", " . $name . " FROM " . $db . "." . $table . " ORDER BY " . $name;
    $result  = mysql_query($query);

    if (!$result)
    {
        printf("-N/A-");
        return;
    }

    $numrows = mysql_num_rows($result);

    if ($_GET[$name]=="On")
        $checked = "checked";
    else
        $checked = "";

    printf("    <input type=\"checkbox\" name=\"%s\" value=\"On\" %s><A HREF=\"printtable.php?fTable=%s\">%s</A>\n", $name, $checked, $table, $descr);

    printf("   <BR>\n");

    printf("   <select name=\"%s\" size=\"1\" class=\"Width\">\n", $index);

    if (empty($_GET[$index]) || $_GET[$index]==0)
        printf("    <option value=\"0\" selected>--- ALL ---</option>\n");
    else
        printf("    <option value=\"0\">--- ALL ---</option>\n");

    if (!empty($_GET[$index]) && $_GET[$index]==-1)
        printf("    <option value=\"-1\" selected>--- GROUP BY ---</option>\n");
    else
        printf("    <option value=\"-1\">--- GROUP BY ---</option>\n");

    while ($row = mysql_fetch_row($result))
    {
        if (!empty($_GET[$index]) && $_GET[$index]==$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>\n");
    printf("   &nbsp;\n", $index);
    
    mysql_free_result($result);

    mysql_close($db_id);
}

function GetMin($field, $table, $db)
{
    $db_id = mysql_connect("hercules.astro.uni-wuerzburg.de", "MAGIC", "d99swMT!");
    if ($db_id==FALSE)
    {
            printf("mysql_connect returned the following error:<br>");
            printf("%s<br>", mysql_error());
            die("");
    }

    $query  = "SELECT MIN(" . $field . ") FROM " . $db . "." . $table;
    $result = mysql_query($query);
    if (!$result)
        return "0";

    $row = mysql_fetch_row($result);

    $min = $row[0];

    mysql_free_result($result);
    mysql_close($db_id);

    return $min;
}

function GetMax($field, $table, $db)
{
    $db_id = mysql_connect("hercules.astro.uni-wuerzburg.de", "MAGIC", "d99swMT!");
    if ($db_id==FALSE)
    {
            printf("mysql_connect returned the following error:<br>");
            printf("%s<br>", mysql_error());
            die("");
    }

    $query  = "SELECT MAX(" . $field . ") FROM " . $db . "." . $table;
    $result = mysql_query($query);
    if (!$result)
        return "0";

    $row = mysql_fetch_row($result);

    $max = $row[0];

    mysql_free_result($result);
    mysql_close($db_id);

    return $max;
}
/*
function GetMin()
{
    $db_id = mysql_connect("hercules.astro.uni-wuerzburg.de", "MAGIC", "d99swMT!");
    if ($db_id==FALSE)
    {
            printf("mysql_connect returned the following error:<br>");
            printf("%s<br>", mysql_error());
            die("");
    }

    $query  = "SELECT MIN(fRunNumber) FROM MyMagic.RunData";
    $result = mysql_query($query);
    if (!$result)
        return "0";

    $row = mysql_fetch_row($result);

    $min = $row[0];

    mysql_free_result($result);
    mysql_close($db_id);

    return $min;
}

function GetMax()
{
    $db_id = mysql_connect("hercules.astro.uni-wuerzburg.de", "MAGIC", "d99swMT!");
    if ($db_id==FALSE)
    {
            printf("mysql_connect returned the following error:<br>");
            printf("%s<br>", mysql_error());
            die("");
    }

    $query  = "SELECT MAX(fRunNumber) FROM MyMagic.RunData";
    $result = mysql_query($query);
    if (!$result)
        return "0";

    $row = mysql_fetch_row($result);

    $max = $row[0];

    mysql_free_result($result);
    mysql_close($db_id);

    return $max;
}
*/

function PrintText($result0)
{
    header("Content-type: application/octet");
    header("Content-Disposition: attachment; filename=query-result.txt");

    while ($row0 = mysql_fetch_assoc($result0))
    {
        foreach ($row0 as $key => $element)
            printf("%s\t", $element);
        printf("\n");
    }
}

function Checkbox($value, $text)
{
    if ($_GET[$value]=="On")
        $checked = "checked";
    else
        $checked = "";

    printf("    <td><input type=\"checkbox\" name=\"%s\" value=\"On\" %s>%s</td>\n", $value, $checked, $text);
}

function CheckWhere($column, $_GET)
{
    foreach ($_GET as $key => $element)
    {
        if ($key==$column)
        {
            if ($element>0)
                printf ("FIXED: %s<BR>", $column);
            return $element;
        }
    }
    return 0;
}

function CheckGroup($column, $_GET)
{
    foreach ($_GET as $key => $element)
    {
        if ($key==$column)
        {
            //if ($element==-1)
            //    printf ("GROUP: %s<BR>", $column);
            return $element;
        }
    }
    return 0;
}

function CheckStatusGroup($column, $_GET)
{
    foreach ($_GET as $key => $element)
        if ($key==$column)
            if ($element==4)
                return -1;
    return 0;
}

function CheckEnumGroup($column, $_GET)
{
    foreach ($_GET as $key => $element)
        if ($key==$column)
            if ($element==3)
                return -1;
    return 0;
}

function CreateMenu($rows)
{
    $menu = "";

    if (empty($_GET["fNumResults"]))
        return;

    if ($_GET["fNumStart"]!=0)
    {
        $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;
        }
        $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='" . $uri . "'>Next >>></A>\n";
    }
    return $menu;
}

function RemoveSortBy($rows)
{
    $menu = "";

    $uri = $_SERVER["REQUEST_URI"];
    $pos = strpos($uri, "fSortBy");
    $amp3=FALSE;
    if ($pos!=FALSE)
    {
        $amp1 = substr($uri, 0, $pos-1);
        $amp2 = substr($uri, $pos);
        $amp3 = strchr($amp2, "&");

        $uri = $amp1;
    }

    return $uri;
}

function FindAlias($alias, $search)
{
    foreach ($alias as $key => $element)
        if ($element==$search)
            return $key;

    return "";
}

function PrintMagicTable($result0, $alias, $rightalign, $limits, $rms, $_GET)
{
    $col   = FALSE;
    $first = TRUE;

    $menu = CreateMenu(mysql_num_rows($result0));

    printf("\n<center>\n<p>%s<P>\n", $menu);
    printf("<table BORDER=\"0\">\n");
    while ($row0 = mysql_fetch_assoc($result0))
    {
        if ($first)
        {
            printf(" <tr BGCOLOR='#C0C0C0'>\n");
            $first = FALSE;
            foreach ($row0 as $key => $element)
            {
                $col = FindAlias($alias, $key);

                $ord="%2B";
                $issort = "";
                if (!empty($_GET["fSortBy"]) && substr($_GET["fSortBy"], 0, -1)==$col)
                {
                    if (substr($_GET["fSortBy"], -1)=="+")
                    {
                        $ord="-";
                        $issort="&nbsp;<IMG SRC='down.gif'>";
                    }
                    else
                        $issort="&nbsp;<IMG SRC='up.gif'>";
                }
                printf("  <th>&nbsp;<A HREF='%s&fSortBy=%s%s'>%s</A>%s&nbsp;</th>\n",
                       RemoveSortBy($_SERVER["REQUEST_URI"]), $col, $ord, $key, $issort);
            }
            printf(" </tr>\n\n");
        }

        if (!$col)
            printf(" <tr BGCOLOR='#E0E0E0'>\n");
        else
            printf(" <tr BGCOLOR='#D0D0D0'>\n");
        $col = !$col;

        foreach ($row0 as $key => $element)
        {
            if (empty($rightalign[$key]))
                printf("  <td align=\"left\">");
            else
                printf("  <td align=\"right\">");

            if (!(empty($limits) && empty($rms)))
            {
                foreach($limits as $key2 => $element2)
                {
                    $mean=$key2 . "Mean";
                    $rms2=$key2 . "Rms";
                    if ($key==$alias[$element2] && !empty($_GET[$mean]))
                    {
                        if ($rms[$key2]=="yes")
                        {
                            if (!empty($_GET[$rms2]))
                            {
                                $min=$_GET[$mean] - $_GET[$rms2];
                                $max=$_GET[$mean] + $_GET[$rms2];
                                if ($min < $element && $element < $max)
                                    printf("<font color='green'>");
                                else
                                    printf("<font color='red'>");
                            }
                        }
                        else
                        {
                            if ($rms[$key2]=="min")
                            {
                                if ($_GET[$mean] <= $element)
                                    printf("<font color='green'>");
                                else
                                    printf("<font color='red'>");
                            }

                            if ($rms[$key2]=="max")
                            {
                                if ($_GET[$mean] >= $element)
                                    printf("<font color='green'>");
                                else
                                    printf("<font color='red'>");
                            }
                        }
                    }

                }
            }

            printf("&nbsp;%s&nbsp;</td>\n", str_replace("&ws;", " ", str_replace(" ", "&nbsp;", $element)));
        }
        printf(" </tr>\n");
    }
    printf("</table>\n");

    /*
     $info = mysql_info();
     if (!empty($info))
     printf("%s<BR>\n", $info);
     */

    printf("<P><B>Number of displayed results: %d</B><P><P>\n", mysql_num_rows($result0));
    printf("%s\n", $menu);
    printf("<P>\n");
    printf("</center>\n");
    printf("</tr><tr class='Block'><td>\n");
}

?>
