#!/usr/bin/perl

# ----------------------------------------------------------------
# John Kerl
# kerl.john.r@gmail.com
# 2005-05-18
# ----------------------------------------------------------------

if (@ARGV < 2) {
	$sum = 0.0;
	while ($line = <>) {
		chomp $line;

		# Strip leading whitespace from line.
		$line =~ s/^\s+//;

		# Skip blank lines.
		next if ($line =~ m/^[ \t]*$/);

		# Get only the first two tokens on the line.
		($f1, $f2) = split /\s+/, $line;

		# Accumulate sum.
		$sum += $f1 * $f2;
	}
	print "$sum\n";
}

elsif (@ARGV == 2) {
	$sum = 0.0;

	$file1 = $ARGV[0];
	$file2 = $ARGV[1];
	die "Couldn't open file \"$file1\"; skipping.\n"
		if (!open(HANDLE1, $file1));
	die "Couldn't open file \"$file2\"; skipping.\n"
		if (!open(HANDLE2, $file2));
	while (($line1 = <HANDLE1>) && ($line2 = <HANDLE2>)) {
		chomp $line1;
		chomp $line2;

		# Skip blank lines.
		next if ($line1 =~ m/^[ \t]*$/);

		# Strip leading whitespace from line.
		$line1 =~ s/^\s+//;
		$line2 =~ s/^\s+//;

		# Get only the first token on the line.
		($f1) = split /\s+/, $line1;
		($f2) = split /\s+/, $line2;

		# Accumulate sum.
		$sum += $f1 * $f2;
	}
	close HANDLE1;
	close HANDLE2;

	print "$sum\n";
}

else {
	die
		"Usage:  $0 {file 1} {file 2}\n" .
		"Or:     $0 {file with two columns}\n" .
		"Or:     $0 with no arguments, standard input having two columns.\n";
}
