#!/usr/local/bin/perl

# Extracts the current US casualty count for Iraq from a Web page

# Create a user agent object
use LWP::UserAgent;
$ua = LWP::UserAgent->new(timeout => 5);
#  $ua = LWP::UserAgent->new();
$ua->agent("MyApp/0.1 ");

# URL of page with casualty numbers
my $url = "http://icasualties.org/Iraq/index.aspx";
$url = $ARGV[0];

my $pattern = $ARGV[1];

my $outfile = "/webapps/mvvp.org/mvvp.org/casualties.txt";
$outfile = $ARGV[2];

# Check once an hour
my $interval = 60 * 60;

   	# Create a request
	my $req = HTTP::Request->new(GET => $url);

	# Pass request to the user agent and get a response back
	my $res = $ua->request($req);

	# Check the outcome of the response
	if ($res->is_success) {
	  my @lines = split( /\n/, $res->content );
	  my $line;
#	  my $line = $res->content;
	  my $i = 0;
	  foreach $line( @lines ) {
		$line =~ s/\r//;
		if ( $line =~ /($pattern)/ ) {
#			print "$line\n";
#			print "$1\n";
			my $found = $1;
			my $count = 0;
			if( $found =~ /([0-9]+)/ ) {
			  $count = $1;
			}
			open( OUTFILE, "> $outfile" ) || die "Can't open outfile\n";
			print OUTFILE "$count\n";
			close( OUTFILE );
			last;
		} else {
#		  print "Not - [$line]\n";
		}
		$i++;
	  }
#	  print "$content\n";
	} else {
	  print $res->status_line, "\n";
	}
