#!/usr/bin/perl

if ($ARGV[0] eq "-a") {
	$allocateonly = true;
	shift(@ARGV);
}

while ($_ = shift(@ARGV)) {
	open (FH, $_) || die ("Error opening $_ ($!)");
	while (<FH>) {
		chomp();
		if (/^READING/ || /^WRITING/) {
			($type, $data, $plugin) = split(/\t/);
			$usecount{"$data-$type $plugin"}++;
			$uses{$data}{$type}{$plugin}++;

		} elsif (/^DATA/) {
			($type, $data) = split(/\t/);

			$type =~ s/^DATA //;

			$accesscount{$type}++;

			$datacount{"$data $type"}++;

			($category) = split(/ /, $type);
			$categorycount{$category}++;

			if ($category eq "REMOTE" || $category eq "OVERHEAD") {
				$cost{"$data"}++;
			}
		} elsif (/maxresident/) {
			($min,$sec) = /(\d+):(\d+).\d+elapsed/;
			$categorycount{'DURATION'} = $min * 60 + $sec;
		}
	}
	close (FH);
}

sub computeallocation() {
	foreach $prop (sort keys %uses) {
		%reads = %{$uses{$prop}{'READING'}};
		%writes = %{$uses{$prop}{'WRITING'}};
		undef %totals;
		undef $totalwrites;
		undef $owner;
		undef %pushees;
		foreach $plugin (sort keys %writes) {
			$totals{$plugin} = $writes{$plugin};
			$totalwrites += $writes{$plugin};
		}
		foreach $plugin (sort keys %reads) {
			$totals{$plugin} += $reads{$plugin};
			if ($reads{$plugin} > $totalwrites) {
				$pushees{$plugin} = 1;
			}
		}
		foreach $plugin (sort keys %totals) {
			$totals{$plugin} = $writes{$plugin} + ($pushees{$plugin} ? $totalwrites : $reads{plugin}); 
		}
		foreach $plugin (sort keys %totals) {
			if (!defined $owner || $totals{$plugin} > $totals{$owner}) {
				$owner = $plugin;
			}
		}
		delete $pushees{$owner};
		print "OWNER\t$prop\t$owner\t";
		print join(",", keys(%pushees));
		print "\n";
	}
}

if ($allocateonly) {
	computeallocation();
	exit();
}

print "-- Category Totals --\n";
foreach $key (sort keys %categorycount) {
	print "$key\t$categorycount{$key}\n";
}

print "-- Access Type Totals --\n";
foreach $key (sort keys %accesscount) {
	print "$key\t$accesscount{$key}\n";
}

print "-- Cost Totals --\n";
foreach $key (sort keys %cost) {
	print "$key\t$cost{$key}\n";
}

print "-- Data Type Totals --\n";
foreach $key (sort keys %datacount) {
	print "$key\t$datacount{$key}\n";
}

print "-- Usage Totals --\n";
foreach $key (sort keys %usecount) {
	print "$key\t$usecount{$key}\n";
}

print "-- Allocation --\n";
computeallocation();
