#!/usr/bin/perl
use strict;
use warnings;

my $fxheader ="#:unix_secs,exaddr,dpkts,doctets,srcaddr,dstaddr,srcport,dstport,prot\n";
my $header=<>;

$header eq $fxheader or die <<ERR;
ERROR: $0 Expected to receive a Flow-Export Data file header like this
$fxheader
but I got :
$header 
instead
ERR


my %store;
my $accuracy = 300; #seconds 
print $fxheader;

while(<>) {
    chomp;
    next if substr($_,0,1) eq "#";
    Export() if ($. % 1e5 == 0);
    my ($utime, $exaddr, $dpkts, $doctets,$srcaddr,$dstaddr,$srcport,$dstport,$prot)=split/,/;
    my $roundtime= int($utime/$accuracy)*$accuracy;

    my $dd_key= join ",", $srcaddr,$dstaddr,$srcport,$dstport,$prot;
    for ($store{$roundtime}{$dd_key}{$exaddr}) {
		$_->[0]+=$dpkts;
		$_->[1]+=$doctets;
    }
}
Export();

sub Export {
    for my $utime (sort {$a<=>$b} keys %store) {
	while(my ($dd_key,$ref_exdata) = each %{$store{$utime}}) {
	    my ($max_oct,$max_pkt)=(0,0);
	    my $witness;
	    while (my ($exaddr,$ref_data) = each %$ref_exdata) {
			if ($max_oct <= $ref_data->[1]) {
				($max_pkt,$max_oct) = @{$ref_data};
				$witness= $exaddr;
			}
			}
			print join(",",$utime,$witness,$max_pkt,$max_oct,$dd_key),"\n";
		}
	}
    %store=();
}



