#!/usr/bin/perl

my $istr = join('+',@ARGV);
my $skip = 0;
while ($istr =~ m/^-/) {
  $istr = substr($istr,1);
  $skip++;
}

my $URL = "http://www.crh.noaa.gov/forecasts/zipcity.php?inputstring=$istr";
#print $URL, "\n";

my $ret = open(P,"wget -q -O - '$URL' |");
#my $ret = open(P,$istr);
if ($ret == undef) { die "Error opening wget.\n"; }

my $wait = 0;
my $match = "";
while (<P>) {
  if (($wait == 0) && (m/alt=\"More than one location/)) { $err = "Multiple locations matched. Try a ZIP code?"; last; }
  if (($wait == 0) && (m/alt=\"Detailed/)) { $wait = 1; }
  next if ($wait == 0);
  if (($wait == 1) && (m/(<b>.*$)/)) { $_ = $1; $match = ""; $wait = 2; }
  next if ($wait == 1);
  $match .= $_ if ($wait == 2);
  if (($wait == 2) && ($match =~ m/<br>$/)) { $wait = 3; }
  next if ($wait == 2);
  if (($wait == 3) && ($skip > 0)) { $skip--; $wait = 1; }
  last if ($wait == 3);
}

$match =~ s/<(\/?)b>//g;
$match =~ s/<br>//g;
$match =~ s/\xa/ /g;
$match =~ s/  / /g;

if ($match eq "") { 
  if ($err eq "") { print "Error requesting forecast for $istr\n"; }
  else { print $err, "\n"; }
}
else { print $match, "\n"; }

