#!/usr/bin/perl

$basecampURL = "http://toys.media.mit.edu/weather/14835";
$camp2URL = "http://toys.media.mit.edu/weather/14836";
$southcolURL = "http://toys.media.mit.edu/weather/14837";
$otherURL = "http://toys.media.mit.edu/weather/14838";

$basecamp = &wwwfetch($basecampURL);
$camp2 = &wwwfetch($camp2URL);
$southcol = &wwwfetch($southcolURL);
$other = &wwwfetch($otherURL);

@x = split("\n",  $basecamp);
@base = (@base, @x);
@x = split("\n",  $camp2);
@base = (@base, @x);
# @x = split("\n",  $southcol);
# @base = (@base, @x);

for (@base){
    next unless /1998/;
    (@data) = split(" ", $_);
    $hmstime = $data[2];
    (@data) = split(" ", substr($_, index($_, ")")+1));
    $temp = $data[1]+0;
    ($h, $m, $s) = split(":", $hmstime);
    $time = $h +($m/60);
    push(@time, $time);
    push(@temp, $temp);

    $goal = $time-6;
    $goal+= 24 if($goal < 0);
    $kg = 1;
    $best = 6;
    for($x=$#time;($kg && $x>=0);$x--){
	$comptime = abs(($time-6)-$time[$x]);
	$comptime += 24 if ($comptime <0);
	if($comptime <= $best){
	    $best = $comptime;
	    $besttemp = $temp[$x];
	}
    }
    $oldtime = ($time-6 > 0) ? $time:($time+18);
    print $oldtime, " $temp $besttemp $best\n";
}



sub wwwfetch {
    local($URL) = @_;
    $URL =~ /http:\/\/([^\/]+)\/(.*)/;
    $hostport = $1; $path = $2;

    ($them, $port) = split(/:/, $hostport);
    $port = 80 unless $port;
    print("Connecting to $them on port $port to get $path\n");
    $AF_INET = 2;
    $SOCK_STREAM = 1;
    
    $sockaddr = 'S n a4 x8';
    
    chop($hostname = `hostname`);
    
    ($name,$aliases,$proto) = getprotobyname('tcp');
    ($name,$aliases,$port) = getservbyname($port,'tcp')
        unless $port =~ /^\d+$/;;
    ($name,$aliases,$type,$len,$thisaddr) =
        gethostbyname($hostname);
    ($name,$aliases,$type,$len,$thataddr) = gethostbyname($them);
    
    $this = pack($sockaddr, $AF_INET, 0, $thisaddr);
    $that = pack($sockaddr, $AF_INET, $port, $thataddr);
    # Make the socket filehandle.
 
    if (socket(S, $AF_INET, $SOCK_STREAM, $proto)) { 
    }
    else {
        return(0);
    }
    
# Give the socket an address.
 
    if (bind(S, $this)) {
    }
    else {
        return(0);
    }
    
    select(S); $|=1;
    select(STDOUT);
    if (connect(S,$that)) {
        print(S "GET /$path perlWWW\n\n\n");
        while(<S>){
            $resp .= $_;
        }
        close(S);
        $resp;
    }
    else{
        return(0);
    }
}
