<HTML>
<HEAD>

<?
    require 'at_dbconnect.php';
    //look for cookie
    $mymagnet=-1;
    if($_COOKIE['magnet'])
    {
        $mymagnet=$_COOKIE['magnet'];
    }
    $ts=time();
    $magnet_count=0;
    $magnet_id="";
    $magnet_x="";
    $magnet_y="";
    // Request all non-expired magnets
    $result = mysql_query(
                "SELECT ID FROM tblMagnets ".
                "WHERE UNIX_TIMESTAMP(Expires)>$ts ");
                 //"AND tblMoves.MovedAt=LastMove");
                 
    if (!$result) {
      echo("error=5");
      exit();
    }
    while ( $row = mysql_fetch_array($result) )
    {

      $magid = $row["ID"];
      //select last move for each magnet
      $moved=mysql_query(
             "SELECT ID, Magnet, Xpos, Ypos, Symbol FROM tblMoves,(SELECT MAX(MovedAt) AS lastmove FROM tblMoves GROUP BY Magnet) AS dismags WHERE tblMoves.MovedAt = dismags.lastmove AND Magnet=$magid");
             //"Select ID, Magnet, Xpos, Ypos, Symbol, Max(MovedAt) FROM tblMoves WHERE Magnet=$magid GROUP BY Magnet");
      if (!$moved) {
      echo("error=5");
      exit();
      }

      while ( $row2 = mysql_fetch_array($moved) )
      {
            $magnet = $row2["Magnet"];
            $xpos   = $row2["Xpos"];
            $ypos   = $row2["Ypos"];
            $symbol   = $row2["Symbol"];
            if($magnet!=$mymagnet||count($row2)<2)
            {
               //echo("<P>$magnet - $xpos - $ypos - $symbol</P>");
               $magnet_count++;
               $magnet_id=$magnet_id.$magnet.",";
               $magnet_x=$magnet_x.$xpos.",";
               $magnet_y=$magnet_y.$ypos.",";

           }
      }
   }
   $magnet_id=rtrim($magnet_id,",");
   $magnet_x=rtrim($magnet_x,",");
   $magnet_y=rtrim($magnet_y,",");
   echo("start=1&mymagnet=$mymagnet&magnet_count=$magnet_count&magnet_id=$magnet_id&magnet_x=$magnet_x&magnet_y=$magnet_y&end=1");
?>
</HEAD>
<BODY>
</BODY>
</HTML>
