#!/usr/bin/perl

use warnings;
use strict;

use File::Spec::Functions qw(splitpath);

my %procs;
my %cmds;
my %stats;

do "parse-data.pl";

my $lasttime = &parse_data(\%procs, \%cmds);
&accumulate_stats(\%procs, \%stats);


my $maxdepth = 100;
foreach my $pid (keys %stats) {
    my $cmd = $procs{$pid}->{cmd};

    #print "Root $pid ", @{$cmd}, "\n";
    &dump_procs($pid, 0, "");
}

sub dump_procs {
    my $pid = shift;
    my $depth = shift;
    my $indent = shift;

    my $proc = $procs{$pid};
    my $cmd = $proc->{cmd}->[$#{$proc->{cmd}}];

    my $time = $proc->{end} == -1 ? $lasttime - $proc->{start} : $proc->{end}-$proc->{start};

    if ($proc->{end} == -1) {
	print "$indent Pid $pid $cmd run $time+ ms...\n";
    } else {
	print "$indent Pid $pid $cmd run $time ms\n";
    }

    foreach (sort { $a cmp $b } keys %{$proc->{read}}) {
        print "$indent   reads ", $_, " ", &avg_freq($proc->{read}->{$_}), " avg ", &avg_size($proc->{read}->{$_}), " bytes \n";
    }
    foreach (sort { $a cmp $b } keys %{$proc->{write}}) {
        print "$indent   writes ", $_, " ", &avg_freq($proc->{write}->{$_}), " avg ", &avg_size($proc->{write}->{$_}), " bytes \n";
    }

    if ($depth < $maxdepth)  {
        foreach my $kid (sort { $a <=> $b } keys %{$proc->{kids}}) {
            &dump_procs($kid, $depth+1, "$indent    ");
        }
    }
}


sub avg_size {
    my $files = shift;

    my $size = 0;
    foreach my $file (@{$files}) {
	$size += $file->{bytes};
    }

    return ($size / ($#{$files} + 1));
}

sub avg_freq {
    my $files = shift;

    if ($#{$files} == 0) {
	return "once only";
    } else {
	my $first = $files->[0]->{time};
	my $last = $files->[$#{$files}]->{time};
	my $dur = $last-$first;
	return sprintf "%s times, once every %d ms", int(@{$files}), ($dur / int(@{$files}));
    }

}

