#!/usr/bin/perl
use warnings;
use strict;

use LWP::UserAgent;
use HTML::TreeBuilder;

my $week  = shift || 1;
my $url   = "http://www.nfl.com/scores?season=2007&week=Week+$week";
my $agent = new LWP::UserAgent;
my $page  = $agent->get($url);
if ( $page->is_success() ) {
    my $root = HTML::TreeBuilder->new_from_content( $page->content() );
    my @all_divs =
      $root->look_down( '_tag', 'div',
        sub { $_[0]->attr('class') and $_[0]->attr('class') eq "scoreBox" } );
    for my $div (@all_divs) {
        my $status = $div->look_down(
            '_tag', 'div',
            sub {
                $_[0]->attr('class')
                  and $_[0]->attr('class') =~ /^scoreBoxHeader/;
            }
        );
        if ($status) {
            next unless ( $status->as_text =~ /FINAL/ );
        }
        my @scores = $div->look_down(
            '_tag', 'div',
            sub {
                $_[0]->attr('class')
                  and $_[0]->attr('class') eq "scoresBoxTeamScore";
            }
        );
        my @teams = $div->look_down(
            '_tag', 'div',
            sub {
                $_[0]->attr('class')
                  and $_[0]->attr('class') eq "scoresBoxTopTeamLogo";
            }
        );
        my @names = map { just_symbol($_) } @teams;
        if ( @scores and @names ) {
            printf "%-3s %-2d - %-3s %-2d\n",
            $names[0], $scores[0]->as_text(),
            $names[1], $scores[1]->as_text();
        }
    }
}

sub just_symbol {
    my $tag    = shift;
    my $href   = $tag->look_down( '_tag', 'a' )->attr('href');
    my $symbol = "XXX";
    $symbol = $1 if ( $href =~ /team=(\w\w\w?)$/ );
    return $symbol;
}