#!/usr/bin/perl -w

@ARGV = ('-') unless @ARGV; #if no command line args then
                            #init @ARGV with the STDIN alias '-'
$rcalloc = {};
$leaks = {};
sub findleaks {
    my $amon = shift;
    if(!open(AMON, $amon)) {
	print "File not found: $amon\n"; #open failed
	die;
    }
    while(my $line = <AMON>) {
	if($line =~ /refcnt\salloc\s+(\S+).*\s(\S+)$/) {
#	    print "<$1> <$2> \n";
	    if($1 > 0) {
#		print "refcnt alloc at line: $line";
		$rcalloc->{$2} = 1;
	    }
	    else {
#		print "refcnt free at line: $line";
		delete $rcalloc->{$2};
	    }
	}
	if($line =~ /reclaim\s+(\S+)/) {
	    if($rcalloc->{$1}) {
#		print "refcnt leak at line: $line";
		$leaks->{$1} = 1;
	    }
	}
    }
}

$leaksites = {};
$allocsites = {};
sub findallocsites {
    my $alog = shift;
    if(!open(ALOG, $alog)) {
	print "File not found: $alog\n"; #open failed
	die;
    }
    while(my $line = <ALOG>) {
	if($line =~ /(\S+)\s+0x(\S+)$/) {
	    if($leaks->{$2}){
		if(!($leaksites->{$1})) {
		    $leaksites->{$1} = 1;
		}
		else {
		    $leaksites->{$1}++;
		}
	    }
	    if(!($allocsites->{$1})) {
		$allocsites->{$1} = 1;
	    }
	    else {
		$allocsites->{$1}++;
	    }
	}
    }
    $totleak = 0;
    $totalloc = 0;
    foreach $key (keys %$leaksites) {
	$nleaks = $leaksites->{$key};
	$nalloc = $allocsites->{$key};
	print "Leak from $key  ($nleaks) ($nalloc)\n";
	$totleak += $nleaks;
	$totalloc += $nalloc;
    }
    foreach $key (keys %$allocsites) {
	if(!($leaksites->{$key})) {
	    $nalloc = $allocsites->{$key};
	    $totalloc += $nalloc;
	    print "Allocation site without leak: $key  ($nalloc)\n";
	}
    }
    print "Total allocations: $totalloc, total leaks $totleak\n";
} 

print "$ARGV[0]\n";
print "$ARGV[1]\n";
findleaks $ARGV[0];
findallocsites $ARGV[1];

#  INPUT_FILE:
#     foreach $ARGV (@ARGV) {
#         if(!open(FILE, $ARGV)) { #try to open file
#             print "File not found: $ARGV\n"; #open failed
#             next IN_FILE; #proceed to next file
#         }
#         print "\nContents of file $ARGV:\n";
#       INPUT_LINE:
#         while($inLine = <FILE>) { #read each line of file into $inLine
#             print $inLine;
#         }
#     }
# fileInput.pl
