#!/usr/bin/env perl
use strict;
use warnings;

my $prbid = $ARGV[0];
my $msmid = $ARGV[1];

my $interval = 900; # 15 mins?

# init
my $ts_cache = undef;
my @avg_per;
my $max_per = 0;
my $min_per = undef;
my $sent_per = 0;
my $recv_per = 0;
my $dup_per = 0;

my $l; #cached results
my $p; # per probe/dst pair

while (<STDIN>) {
	chomp();					
	my ($ts,$sent,$recv,$dup,$minrtt,$avgrtt,$maxrtt) = split(/;/,$_);
	$ts = int($ts / $interval)*$interval;
	if (! $ts_cache ) {
		$ts_cache = $ts;
	}
	if ( $maxrtt > $max_per ) { $max_per = $maxrtt };
	if ( !$min_per || $minrtt < $min_per ) { $min_per = $minrtt };
	push @avg_per, $avgrtt;
	$sent_per+=$sent;
	$recv_per+=$recv;
	$dup_per+=$dup;

	if ($ts_cache != $ts) {
		calc_avg();
		$ts_cache = $ts;
	}
}
calc_avg();

sub calc_avg {
	my $avg = 0;
	if (@avg_per) {
		for (@avg_per) {
		$avg+=$_;
		}
		$avg /= scalar @avg_per;
	} 
	$l->{$prbid}{$msmid}{$ts_cache} = {
		minrtt => $min_per,
		avgrtt => $avg,
		maxrtt => $max_per,
		loss_frac => $sent_per?$recv_per/$sent_per:0,
		dup_frac => $sent_per?$dup_per/$sent_per:0 };
	push @{$p->{$prbid}{$msmid}},{
		minrtt=>$min_per,
		avgrtt=>$avg,
		maxrtt=>$max_per };
=cut
	printf("%s\t%s\t%s\t%.2f\t%.2f\t%.2f\t%.3f\t%.3f\n", 
		$prbid,
		$msmid,
		$ts_cache,
		$min_per,
		$avg,
		$max_per,
		$sent_per?$recv_per/$sent_per:0,
		$sent_per?$dup_per/$sent_per:0 );
=cut

	@avg_per = ();
	$max_per = 0;
	$min_per = undef;
	$sent_per = 0;
	$recv_per = 0;
	$dup_per = 0;
}

foreach my $prbid (sort keys %$l) {
	foreach my $msmid (sort keys %{$l->{$prbid}} ) {
		# calculate the averages over the entire interval for each src/dst pair
		my ($avg_min_pair,$avg_avg_pair,$avg_max_pair) = (undef,undef,undef);
		if ( @{$p->{$prbid}{$msmid}} ) {
			foreach my $val (@{$p->{$prbid}{$msmid}}) {
				$avg_min_pair += $val->{minrtt};
				$avg_avg_pair += $val->{avgrtt};
				$avg_max_pair += $val->{maxrtt};
			}
			$avg_min_pair /= scalar @{$p->{$prbid}{$msmid} };
			$avg_avg_pair /= scalar @{$p->{$prbid}{$msmid} };
			$avg_max_pair /= scalar @{$p->{$prbid}{$msmid} };
		}
		foreach my $ts (sort keys %{ $l->{$prbid}{$msmid} } ) {
			my $ref = $l->{$prbid}{$msmid}{$ts};
			printf("%s\t%s\t%s\t%.2f\t%.2f\t%.2f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n", 
				$prbid,
				$msmid,
				$ts,
				$ref->{minrtt},
				$ref->{avgrtt},
				$ref->{maxrtt},
				$ref->{loss_frac},
				$ref->{dup_frac},
				$avg_min_pair?$ref->{minrtt}/$avg_min_pair:1,
				$avg_avg_pair?$ref->{avgrtt}/$avg_avg_pair:1,
				$avg_max_pair?$ref->{maxrtt}/$avg_max_pair:1,
			);
		}
	}
}

__END__
cat 4.1008.2010.50.log | perl -F\\\; -lane'print join("\t",$F[1],$F[2],$F[3],$F[4],$F[5],$F[6]) if ($F[0]<1292630400 && $F[0] >1292544000)'

1292198414;3;3;0;141.059;143.583;142.35499999999999
1292198550;3;3;0;141.35599999999999;142.723;142.02500000000001
1292198717;3;3;0;142.16200000000001;144.187;142.85300000000001

