#!/usr/bin/perl -w

use lib '.';
use strict;
use Stat;

my %data;
my %calc;

my @dr;
my @H;
my @min;
my @mid;
my @max;
my @mpe;

sub nsort() {
    $a <=> $b
}

sub pr_data() {
    for my $dr ( sort nsort keys %data ) {
	my $v = $data{$dr};
	my $cnt = 0;
	for my $th (sort nsort keys %$v) {
	    $cnt = $$v{$th};
	    printf "%4.1f %4.1f %5d\n", $dr, $th, $cnt;
	}
    } 
}

sub calc() {
    for my $dr ( sort nsort keys %data ) {
	my $v = $data{$dr};
	my $cnt = 0;
	my @a;
	my @h;
	my $str = "";
	for my $th (sort nsort keys %$v) {
	    $cnt = $$v{$th};
	    push @a, $th;
	    push @h, $cnt;
	    $str .= " + $cnt*$th";
	}
	my $stat = Stat::stat(\@a, \@h);
	if ($$stat[0] > 1 && $$stat[4] > 0) {
	    $calc{$dr} = [ @$stat ];
	}
	push @dr, $dr;
	push @H, $$stat[0];
	push @min, $$stat[1];
	push @mid, $$stat[2];
	push @max, $$stat[3];
	push @mpe, $$stat[2] + $$stat[4];
	#printf "%5.1f  %4d / %4.1f %5.2f %4.1f / %6.3f / (0%s)\n", $dr, @$stat, $str;
    } 
}

sub pr_calc() {
    for my $dr ( sort nsort keys %calc ) {
	my $stat = $calc{$dr};
	printf "%5.1f  %4d / %4.1f %5.2f %4.1f / %6.3f\n", $dr, @$stat;
	#print Dumper($stat};
    }
}

sub pr_line( @ ) {
    my @a = @_;
    for (my $ix = 0; $ix < @dr; $ix++) {
	my $x = $dr[$ix];
	my $y = $a[0];
	my $xx = $x;
	for (my $ax = 1; $ax < @a; $ax++) {
	    $y += $a[$ax] * $xx;
	    $xx *= $x;
	}
	printf("  %4.1f %5.2f %4.1f\n", $x, $y - $x, $y);
    }	
}

sub do_linreg() {
    my @a;
    
    @a = Stat::stat_linreg(\@dr, \@min, \@H);
    printf("min: %7.4f %7.4f\n", $a[0], $a[1]);
#    pr_line(@a);
    
    @a = Stat::stat_linreg(\@dr, \@mid, \@H);
    printf("mid: %7.4f %7.4f\n", $a[0], $a[1]);
#    pr_line(@a);

    @a = Stat::stat_linreg(\@dr, \@max, \@H);
    printf("max: %7.4f %7.4f\n", $a[0], $a[1]);
#    pr_line(@a);

    @a = Stat::stat_linreg(\@dr, \@mpe, \@H);
    printf("mpe: %7.4f %7.4f\n", $a[0], $a[1]);
#    pr_line(@a);
}

sub get_data() {
    #my $old;
    while (<>) {
	my ($dr, $th, $cnt) = split;
	#if (!defined($old)) { $old = $dr; }
	#if ($old != $dr) { last; }
	$data{$dr}{$th} = $cnt;
    }
}

sub main() {
    get_data();

    #pr_data();
    calc();
    pr_calc();
    do_linreg();
}

main();
