#!/usr/local/bin/perl5 -w

use Getopt::Std;

getopts('h');

$div = $opt_h ? 3600 : 900;
$div2 = $div / 2;

open(HIS, "tail -1000 /news/lib/history|") or die("cannot tail history: $!\n");
$av = 0;
$count = 0;
@hist = (0) x 79;
while ( <HIS> ) {
    chomp;
    @fields = split(/\t/);
    next unless $fields[2];
    ($i, $p) = (split(/~/, $fields[1]))[0,2];
    $firstar = $i unless $firstar;
    $d = $i - $p;
    next if $d < 0;
    $h = int(($d + $div2) / $div);
    $h = 78 if $h > 78;
    $hist[$h]++;
    push(@all, [$d, $h]);
    $av += $d;
    $min = $d if ( !defined($min) || $d < $min );
    $max = $d if ( !defined($max) || $d > $max );
    $count++;
}
$av /= $count;
close(HIS);

$speed = $count / ($i - $firstar);

$m = 1;
foreach $h ( @hist ) {
    $m = $h if $h > $m;
}

$sens = $scount = 0;
foreach $a ( @all ) {
    if ( $a->[1] != 78 && $hist[$a->[1]] > $m / 10 ) {
	$sens += $a->[0];
	$scount++;
    }
}
$sens /= $scount if $scount;

sub tohms {
    my($time) = @_;
    my($h, $m, $s);

    $h = int($time/3600);
    $time -= $h*3600;
    $m = int($time/60);
    $time -= $m*60;
    ($h, $m, int($time+.5));
}

$latest = time - $i;

printf "Sensible Lag: %02d:%02d:%02d ($sens, $scount measures)\n",
    tohms($sens);
print  "Articles/sec: $speed\n";
printf "Minimum  Lag: %02d:%02d:%02d ($min)\n", tohms($min);
printf "Average  Lag: %02d:%02d:%02d ($av)\n", tohms($av);
printf "Maximum  Lag: %02d:%02d:%02d ($max)\n", tohms($max);
printf "Latest Art arrived: %02d:%02d:%02d ($latest) ago\n", tohms($latest);

$m /= 20;
for $i ( 0 .. 20 ) {
    for $j ( 0 .. 78 ) {
	if ( $hist[$j] > (20-$i)*$m ) {
	    print "*";
	}
	else {
	    print " ";
	}
    }
    print "\n";
}
if ( $opt_h ) {
    print <<FOOTER;
01234567891 1  1    2    2    3    3    4    4    5    5    6    6    7    7 7>
          0 2  5    0    5    0    5    0    5    0    5    0    5    0    5 7
FOOTER
}
else {
    print <<FOOTER;
0   1   2   3   4   5   6   7   8   9   1   1   1   1   1   1   1   1   1   1 >
                                        0   1   2   3   4   5   6   7   8   9
FOOTER
}
printf <<FOOTER, $m;
Histogram of lag of arriving articles. One character is %.2g articles
FOOTER

