#!/usr/athena/bin/perl

# print_mem_usage
open(TOP, ">/tmp/topout") || die;
close(TOP);
if (! fork) {
    exec("top -b -u -dinfinity -s1 >> /tmp/topout");
}
else {
    open(TOP, "/tmp/topout");
}

while (<>) {
    chop;
    &print_mem_usage(split(' ', $_, 4));
}

sub print_mem_usage {
    local($pid, $file, $line, $message) = @_;
    local(@stats);
    local($rin, $size);
    local($nfound);
    local($flushing) = 1;
    local($readline);

    while ($flushing || (! $size)) {
	if ($readline = <TOP>) {
	    if (! $flushing) {
		@stats = split(' ', $readline);
		if ($stats[0] eq "$pid") {
		    ($size = $stats[4]) =~ s/K//;
		}
	    }
	}
	else {
	    $flushing = 0;
	}
    }

    if ($size > $last_mem_usage) {
	print "**";
    }
    print "At $file line $line ($message): $size\n";
    $last_mem_usage = $size;
}
