#!/usr/bin/perl

$i = 0;
if ($#ARGV == 0)
   {
   $i = $ARGV[0];
   }
print "Starting with zip code ";
printf("%05d",$i);
print "\n";

$telem = 0;

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
						localtime(time);
$dateStr = sprintf("%04d-%02d-%02d_%02d%02d%02d",$year+1900, $mon+1, $mday,$hour,$min,$sec);
open (OUT, ">SnaggedZips-$dateStr.txt");
open (OUT2, ">SnaggedZipsPreferredOnly-$dateStr.txt");
if ($telem)
   {
   open (OUT3, ">telem.txt");
   }
print "Working. Created output files.\n";

while ($i < 99999)
      {
      $zip = sprintf("%05d",$i);
      $page = `curl -s -d ctystzip=$zip http://www.usps.com/cgi-bin/zip4/ctystzip2`;
      $ok = 0;

      if ($page =~ /could not be found/i)
	 {
	  # no zip code there.
	  # maybe we should do something else?
	$ok = 1;
	 }
      elsif ($page =~ /Opening Usps Ams Api/i)
	 {
	   # error. Let's try again.
	  $ok = 0;
	 }
      elsif ($page !~ /(?!not)...\saccept/i)
      	{
	# seems to be a post office error -- no acceptable
	# city name for this zip
	print "Hit apparent PO Bug!\n";
	$ok = 1;
	}
      else
	  {
	  $start = index($page,"-<BR>")+5;
	  $end = index($page, "\n", $start);
	  $thisData = substr($page,$start,$end-$start);
	  @zipRecs = split(/<BR>/i, $thisData);
	  foreach $thisLine (@zipRecs)
		{
		if ($telem)
		   {
		     print OUT3 "$thisLine\n";
		   }
		$city = &trim(substr($thisLine,0,27));
		$state = &trim(substr($thisLine,27,9));
		$status = &trim(substr($thisLine,36,20));
		$city = &firstLetterUpper($city);
		if (($status !~ /not acceptable/i) && (length($city)>1))
			{
			print OUT "$zip\t$city\t$state\t";
			if ($status =~ /default/i)
				{
				print OUT "P";
				print OUT2 "$zip\t$city\t$state\tP\n";
				print "$zip\t$city\n";
				}
			else
				{
				print OUT "A";
				}
			print OUT "\n";
		    }
		$ok = 1;
		}
	  }
      if ($ok == 1)
	 {
	  if ($i % 25 == 0)
	    {
	    print "Working... $zip\n";
	    }
	  $i++;
	  if ($i % 5 == 0)
	     {
	       sleep 1;
	     }
	 }
      }
close(OUT);
close(OUT2);
if ($telem)
   {
   close(OUT3);
   }
$res = `gzip SnaggedZips-$dateStr.txt`;
$res = `gzip SnaggedZipsPreferredOnly-$dateStr.txt`;

exit(0);

sub firstLetterUpper {
	my ($string)=@_;
    $string =~ tr/A-Z/a-z/;
    $string =~ s/\b(\w)(\w+)/\u$1$2/g;
    return $string;
}

sub trim {
	my ($string) = @_;
	$string =~ s/^\s+//;
    $string =~ s/\s+$//;
	return $string;

}

