#!/usr/bin/perl -w

use strict;
use Digest::MD5 qw(md5_hex);
use Digest::SHA qw(sha1_hex);

my $line;
my $award = 0;
my @nominees = ();

sub sort_winners {
	my $hash = shift;
	@nominees = sort {
		$a->{$hash} cmp $b->{$hash};
	} @nominees;
}

sub show_winners {
	my $hash = shift;
	sort_winners($hash);
	print "   Lowest ", uc $hash, ": ", $nominees[0]->{$hash}, " ", $nominees[0]->{"name"}, "\n";
	print "  Highest ", uc $hash, ": ", $nominees[$#nominees]->{$hash}, " ", $nominees[$#nominees]->{"name"}, "\n";
}

sub text_winners {
	my $award = shift;
	print "FOR ", $award, ", THE WINNER IS:\n";
	# Sort by md5 hash
	show_winners("md5");
	show_winners("sha1");
}

sub tsv_winners_hash {
	my $hash = shift;
	sort_winners($hash);
	print "\t", $nominees[0]->{"name"}, "\t", $nominees[$#nominees]->{"name"};
}

sub tsv_winners {
	my $what = shift;
	print $what;
	tsv_winners_hash("md5");
	tsv_winners_hash("sha1");
	print "\n";
}

sub html_winners {
	my $award = shift;
	sort_winners("md5");
	print "<dt>", $award, "</dt>\n";
	print "<dd>", $nominees[0]->{"name"}, "</dd>\n";
}

while ($line = <>) {
	# Remove the newline at the end the semi-smart way
	$line = substr $line, 0, -1 if (substr($line, -1) eq "\n");
	$line = substr $line, 0, -1 if (substr($line, -1) eq "\r");
	if (!$award) {
		$award = $line;
	} elsif ($line eq '') {
		# Empty line means start a new award next line
		if (scalar @nominees > 0) {
			# We have entries, so display 'em
			tsv_winners($award);
			@nominees = ();
		}
		$award = 0;
	} else {
		# Otherwise, add
		push @nominees, {
			"name" => $line,
			"md5" => md5_hex($line),
			"sha1" => sha1_hex($line)
		};
	}
}
if (scalar @nominees > 0) {
	# We have entries, so display 'em
	tsv_winners($award);
}
