#!/usr/bin/perl

use CGI;
use strict;
use imdb;

my $site_title = "Jared Burke's Movie Ratings";
my $site_bgcolor = "#FFFFFF";
my $site_text = "#000000";
my $site_link = "#0000DD";
my $site_alink = "#0000FF";
my $site_vlink = "#0000AA";
my $site_font = "Tahoma";
my $graph_color = "#FF0000";
my $graph_border = "#000000";
my $graph_width = "600";
my $graph_bgcolor = "#BBBBBB";
my $datafile = "movies.txt";
my $total_votes = 0;

my ($s, @titles, %votes, $title);

import_movies();
print_results();

sub import_movies() {
	open(INFILE, "<", "$datafile")
		or die "read error: $datafile $!";
	@titles = <INFILE>;
	close(INFILE);
	foreach $s (@titles) {
		$total_votes = $total_votes + 1;
	}
}

sub print_results() {
	print "Content-type: text/html\n\n";
	print "<html><head><title>$site_title: Results</title></head>\n";
	print "<body bgcolor=$site_bgcolor text=$site_text link=$site_link alink=$site_alink vlink=$site_vlink>\n";
	print "<font face=$site_font><h1>$site_title: Results</h1><br><br><a href=index.cgi>Vote again</a><br>\n";
	print "<table width=$graph_width bgcolor=$graph_bgcolor><tr><td>\n";
	foreach $title (@titles) {
		chomp($title);
		$votes{$title} = $votes{$title} + 1;
	}
	foreach $title (sort { $votes{$b} <=> $votes{$a} } keys(%votes)) {
		print "<b>$title</b>: $votes{$title} ";
		draw_graph($votes{$title});
		print "<br>\n";
	}
	print "</td></tr></table><br>";
	print "Total votes: $total_votes\n";
	print "</body></html>";
}

sub draw_graph() {
	my $count = shift;
	my $percentage = ($count / $total_votes);
	my $width = ($percentage * $graph_width);
	$width = round($width);
	print "<table bgcolor=$graph_border width=$width height=10><tr><td bgcolor=$graph_color></td></tr></table>\n";
}

sub round() {
	my($number) = shift;
	return int($number + .5 * ($number <=> 0));
}