#!/usr/local/bin/perl

# perl script to download football scores, encode each team with a
# unique binary identification and store the week number, teams and
# score difference in the output file 'football.out'

# Last modified November 13, 1998 by Bill Goodwine

use LWP::Simple;

$weeks = 10;
$base = "http://www.cnnsi.com/football/nfl/schedules/1998/";

open OUT, "> football.dat";
foreach $week (1..$weeks) {
  print STDERR "\n\nDownloading scores for week $week...\n\n";
  foreach $_ (split(/\n/,get($base . "week" . $week . ".html"))) {
    if(/>([\w\s\.]+)\s+at\s+([\w\s\.]+)<.*?SIZE.*?>(\d+)-(\d+)/) {
      print STDERR "$1 at $2: $3 - $4\n";
      unless(defined $teams{$1}) {$teams{$1}=($count++)}
      unless(defined $teams{$2}) {$teams{$2}=($count++)}
      print OUT "$week   ",&bin($teams{$1}),"   ", &bin($teams{$2}),"   ",$3-$4,"\n";
    } 
  }
}
close OUT;

# binary encoding for team numbers
sub bin {
  my $val = shift;
  $val -= ($bin[4] = int($val/16.0))*16;
  $val -= ($bin[3] = int($val/8.0))*8;
  $val -= ($bin[2] = int($val/4.0))*4;
  $val -= ($bin[1] = int($val/2.0))*2;
  $bin[0] = int($val/1.0);
  return "$bin[4] $bin[3] $bin[2] $bin[1] $bin[0]";
}
