#!/n/gnu/bin/perl
#
# computes grades
# has to be run on the same directory as rcamp?.txt

use CGI;
$PUBLIC=".";

$valid_games = 0;
# le^ dos arquivos
foreach $i (0 .. 9) {
    # le^ terceira linha, se houver
    $third_line = `head -3 rcamp$i.txt | tail -1`;
    next if $third_line !~ /^\(\(/;
    $valid_games++;
    # destrincha e bota valores no hash
    @items = split('\) \(', $third_line);
    foreach $item (@items) {
	$item =~ /([\w-]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/;
	$name = $1;
	$vito = $2;
	$empa = $3;
	$derr = $4;
	$desc = $5;
	$rcamp{$i}{$name}{V} = $vito;
	$rcamp{$i}{$name}{E} = $empa;
	$rcamp{$i}{$name}{D} = $derr;
	$rcamp{$i}{$name}{X} = $desc;
	$rcamp{$i}{$name}{S} = $vito + $empa + $derr + $desc;
	$pontos{$name} = 0;
	$partidas{$name} = 0;
	$desc{$name} = 0;
    }
}

# computa pontos brutos
# vitoria vale 2, empate vale 1
# computa tb subsidios para ver funcionamento minimo

foreach $i (0 .. 9) {
    foreach $name (keys %{$rcamp{$i}}) {
	$pontos{$name} +=
	    2*($rcamp{$i}{$name}{V}) +
		$rcamp{$i}{$name}{E};
        $partidas{$name} += $rcamp{$i}{$name}{S};
        $desc{$name} += $rcamp{$i}{$name}{X};
    }
}

# calcula max e min entre os que tem func. min.

$max = 0;
$min = 20*scalar(keys %pontos);

foreach $name (keys %pontos) {
    if (10*$desc{$name} <= $partidas{$name}) {
        $max = $pontos{$name} if $max < $pontos{$name};
        $min = $pontos{$name} if $min > $pontos{$name};
    }
}

# calcula notas

foreach $name (keys %pontos) {
    if (10*$desc{$name} <= $partidas{$name}) {
        $nota{$name} = 5 + 5.0*($pontos{$name}-$min)/($max - $min);
    } else {
        $nota{$name} = 5.0*($partidas{$name}-$desc{$name})/$partidas{$name};
    }
}

# parte de gerar html

$query = new CGI;
$title = "Notas";
print $query->start_html($title);
print $query->h1($title);

print $query->p("Número de camps válidos: $valid_games");

print $query->p("Max.pontos = $max, Min.pontos = $min");

print "\n<table>\n";
print "<tr><th>Jogador" .
    "<th>" . join("<th>", 0 .. 9) .
    "<th>Total" .
    "<th>Nota\n";
foreach $name (sort { $nota{$b} <=> $nota{$a} } keys %nota) {
    print "<tr><td>$name";
    foreach $i (0 .. 9) {
	print "<td>";
	print 2*($rcamp{$i}{$name}{V}) +
	    $rcamp{$i}{$name}{E};
    }
    print "<td>$pontos{$name}";
    print "<td>";
    printf "%4.1f", $nota{$name};
    print "\n";
}

print "</table>\n";
print $query->end_html;



