#!/usr/bin/perl -w

use strict;
use warnings;

my $dbfile='body';
my $html_out='body.html';

my $title='???';


sub header {
	print <<END
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<LINK href="../../styl.css" rel=stylesheet type="text/css">
<TITLE>$title</TITLE>
</HEAD>
<BODY>
<H1>$title</H1>
END
	;
}

sub footer {
	print "</BODY>\n</HTML>\n";
}

my %h;

sub chew_input {
	my ($name, $task, $score, $serie, $subtask);

	while (<>) {
		chomp;
		if (/^\s*$/) {
			next
		}
		elsif (/^#/) {
			$title = substr $_, 1
		}
		elsif (/^!/) {
			$name = substr $_, 1
		}
		elsif (/^\s*.+\.[^\s]+\s+\d+(\.\d)?\s*$/) {
			($task, $score) = split;
			($serie, $subtask) = split /\./, $task;
			$h{$name}{$serie}{$subtask} = $score;
		}
		else {
			die "Error parsing line: $_";
		}
	}
}

my %serl;
my %taskl;
my %total;
my %pisemka;

sub munch_data {
	my ($name, $ser, $task);

	foreach $name (keys %h) {
		foreach $ser (keys %{$h{$name}}) {
			$serl{$ser} = 1;
			foreach $task (keys %{$h{$name}{$ser}}) {
				$total{$name} += $h{$name}{$ser}{$task};
				if ($ser eq 'p') {
					$pisemka{$name} += $h{$name}{$ser}{$task};
				}
			}
		}
	}
	foreach $ser (keys %serl) {
		foreach $name (keys %h) {
			foreach $task (keys %{$h{$name}{$ser}}) {
				$taskl{$ser}{$task} = 1;
			}
		}
	}
}

sub name_cmp {
	my @xa = split / /, $a;
	my @xb = split / /, $b;
	$xa[1] cmp $xb[1];
}

sub print_table {
	my ($name, $task, $score, $serie, $subtask);

	print '<TABLE border="1"><THEAD>' . "\n";
	print '<TR><TH rowspan=2>Jméno';
	foreach my $s (sort keys %serl) {
		my @ar = keys %{$taskl{$s}};
		my $sz = @ar;
		print "<TH colspan=$sz>Série $s";
	}
	print "<TH rowspan=2>Total\n<TR>\n";

	foreach $serie (sort keys %serl) {
		foreach $task (sort keys %{$taskl{$serie}}) {
			print "<TH>$task";
		}
		print "\n";
	}
	print "<TBODY>\n";

	foreach $name (sort name_cmp keys %h) {
		print "<TR><TD>$name\n";
		foreach $serie (sort keys %serl) {
			foreach $task (sort keys %{$taskl{$serie}}) {
				print "<TD>";
				print $h{$name}{$serie}{$task} if defined  $h{$name}{$serie}{$task};
			}
			print "\n";
		}

		my $p = 0;
		$p = $pisemka{$name} if defined $pisemka{$name};
		my $tot = $total{$name};
		$tot -= 2*(10-$p) if $p < 10;
		print "<TD>$tot (" . ($total{$name}-$p) . "+" . "$p)\n";
	}
	print "</TABLE>\n";
}


chew_input;
munch_data;
header;
print_table;
footer;


