#!/afs/athena/contrib/perl/perl


# attach bitbucket

open (FI, "/mit/bitbucket/zephyr-log/.stats") || die "Couldn't open file: $!";
open (FO, ">/tmp/.statemp") || die "Couldn't open file: $!";

# -w -- only look at values within past week
# -i [instance] -- how many msgs to instance by user
# -u [username] -- how many msgs by user to each instance

if ($ARGV[0] eq "-w") {
    $w++;
    shift @ARGV;
}
if ($ARGV[0] eq "-i") {
    $i_mode++;
    shift @ARGV;
    $instance = shift @ARGV if @ARGV;
} elsif ($ARGV[0] eq "-u") {
    $u_mode++;
    shift @ARGV;
    $user = shift @ARGV if @ARGV;
} else {
    &usage;
}
sub usage {
    print STDERR "Usage: $0 -w -i [instance] -u [username]\n";
    exit 1;
}

$lwee = $^T - 60*60*24*7;
$num_values = 0;

while (<FI>) {
    ($tl, $sigl, $ml, $usnam, @rest) = split;
    $inst = pop(@rest);
    $tim = pop(@rest);

    next if ($w && ($tim < $lwee));
    
    if ($u_mode) {
	if (!$user) {
    if (!$UIN{$usnam}) {
$num_values++;
	}
	    $UIN{$usnam}++;
	    $header = "zwriters";
	} elsif ($usnam eq $user) {
    if (!$UIN{$inst}) {
$num_values++;
}
	    $UIN{$inst}++;
	    $header = "instances written to by $user";
	    $ch = 1;
	    #print $inst;
	}
    } else {  # if ($i_mode)
	if (!$instance) {
	    if (!$UIN{$inst}) {
	print "$inst\n";
    $num_values++;
	}
	    $UIN{$inst}++;
	    
	    # use only the first 15 chars
	    # $inst = substr($inst, 1, 15);
	    $inst =~ s/\@/=/g;
	    $header = "instances";
	} else {
	    if ($inst eq $instance) {
	$num_values++ if !($UIN{$usnam});
		$UIN{$usnam}++;
		$header = "zwriters to $instance";
		print $usnam;
	    }
	}
    }
}

$header = $header." for the past week" if $w;
print "Done with the .stats sorting...\n\n\n\n";
print "num elements: ", scalar(@UIN), "\n";

$x = 1;
sub byvalue { $UIN{$b} <=> $UIN{$a}; }
foreach (sort byvalue keys %UIN) {
    print "rp";
    $item = $_;
    print $num_values;

    $q = $UIN{$item};
    print $q;
#    chop $item if $user;
#	if ($x < 101) {
    print (FO "$x:$item:$q\n");
#}
    $x++;
}
close (FO);
    
#$num_values = 100 if $num_values > 100;
