#!/usr/bin/perl -w

# fedex -- by greenfly <greenfly@greenfly.org>
# This program will print out tracking information for 
# an Fedex tracking number passed as an argument
# usage: fedex <tracking number> [<tracking number>...]

use LWP::UserAgent;

my $language = "english";
my $country = "us";
foreach(@ARGV)
{
   my $tracking_number = $_;
   my $ua = new LWP::UserAgent;
   my $req = new HTTP::Request GET => "http://www.fedex.com/cgi-bin/tracking?action=track&language=$language&ascend_header=1&cntry_code=$country&initial=x&mps=y&tracknumbers=$tracking_number";
   my $res = $ua->request($req);
   if($res->is_success)
   {
      $fedex = $res->content;
   }
# end grabbing html

   use HTML::Parser;

   our $rowcount = -1;
   our $colcount = 0;
   our @table;
   our @text;

# set up our html parser
   my $p = HTML::Parser->new(api_version => 3,
	 start_h => [\&t_start_handler, "self,tagname,attr"],
	 end_h => [\&t_end_handler, "self,tagname,attr"],
	 report_tags => [qw(tr td th)],
	 );
   $p->parse($fedex || die) || die $!;
# at this point the %table array of arrays should be populated

# start outputting
   my $start = 0;
   foreach $row (0 ..  $#table)
   {
      last if($start && (! defined $table[$row]));
      if($table[$row] && ($table[$row][0] =~ /^Date\/time/i))
      {
	 $start = 1;
      }
      if($start == 1)
      {
#uncomment if you want to pretty up the output
	 if($table[$row][0] =~ /^\W+$/){print "\t";}
	 foreach $col (@{ $table[$row] })
	 {
#uncomment if you want to pretty up the output
	    if($col eq "Status"){print "\t\t";}
	    if($col eq "Location"){print "\t\t\t";}

	    print "$col\t";
	 }
	 print "\n";
      }
   }
   print "-" x 80;
   print "\n";
}



############################################################
# subroutines start here
############################################################

sub t_start_handler
{
    my($self, $tag, $attr) = @_;
    if($tag eq 'tr')
    {
       $rowcount++;
       $colcount = 0;
    }
    if($tag eq 'td' || $tag eq 'th')
    {
       $self->handler(text => \&hash_text, "dtext");
       $colcount++;
    }
}

sub hash_text
{
   my $text = shift;
   chomp $text;
   $text =~ s/\s{2,}//g;
#   print $text;
   if($text =~ /^$/){ return };
   if($text =~ /^\s+$/){ return };
   push(@{ $table[$rowcount] }, $text);
}

sub t_end_handler
{
    my($self, $tag) = @_;

    $self->handler("text", undef);
    $self->handler("start", \&t_start_handler);
    $self->handler("end", undef);
}

