<?
/*

  Script to fix the buggy headers from Gadspot NC800.

  Angel Carpintero <ack@telefonica.net>

*/


function fetchURL( $url ) {
   $url_parsed = parse_url($url);
   $host = $url_parsed["host"];
   $port = $url_parsed["port"];
   if ($port==0)
       $port = 80;
   $path = $url_parsed["path"];
   if ($url_parsed["query"] != "")
       $path .= "?".$url_parsed["query"];

   $out = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";

   $fp = fsockopen($host, $port, $errno, $errstr, 30);

   fwrite($fp, $out);
   $body = true;
   while (!feof($fp)) {
       $s = fgets($fp, 1024);
       if ( $body )
           $in .= $s;
       if ( $s == "\r\n" )
           $body = true;
   }
  
   fclose($fp);
  
   return $in;
}

 $camera = fetchURL("http://camera_ip:8080/snapshot.html");
 $camera = str_replace("HTTP/1.1 200 OK\r\n","",$camera);
 $camera = str_replace("connection: close\r\n","",$camera);

 $pos = strpos($camera,"CONTENE-LENGTH: ");
 $pos += 16;
 $posini = $pos;

 while ($camera[$pos] != "\n"){
	$pos++;
 }

 $pos_length = $pos - $posini;

 $content_length = substr($camera,$posini,$pos_length-1);

 $pos++;

 while ($camera[$pos] != "\n"){
        $pos++;
 }
 
 $pos++; 

 $end = strlen($camera);
 $camera_fix = substr($camera,$pos,$end);
 header("Content-Length: $content_length");	
 header("Content-Type: image/jpeg");
 echo $camera_fix;
?>