#!/usr/bin/perl

$event_filter = "[rs-]";
@type_filter = ("tcp", "udp", "cbr");

if (@ARGV < 1) {
    printf "usage plot_tp.pl <trace file> [node1, ...]\n";
    exit;
}

%packet_source = ();
$granularity = 0.5;
@p_data = ();
@p_time = ();
@trace_list = ();
@trace_type = ();

$tracename = shift;

open(infile, $tracename) or die "couldn't open $tracename";
while ($line = <infile>) {
    next if ($line !~ /^$event_filter/);
    $cont = 0;
    foreach $t (@type_filter) {
        if ($line =~ /$t/) {
	    $cont = 1;
	    last;
	}
    }
    next unless ($cont);

    @entry = split(/[\s\(\)\[\]]+/, $line);

    $event = $entry[0];
    $time = $entry[1];

    # check for trace format and parse entry
    if ($entry[2] =~ /_+(\d+)_+/) { # mobile
	$to = $1;
	$pktid = $entry[7];

	if ($event ne "r") {
	    $packet_source{$pktid} = $to;
	    next;
	}

	die "packet error $pktid" if ($packet_source{$pktid} == undef);
	$from = $packet_source{$pktid};
	$type = $entry[8];
	$size = $entry[9];
	$packet_source{$pktid} = $to;
    } else {                        # standard
	$to = $entry[3];
	$pktid = $entry[11];

	if ($event ne "r") {
	    $packet_source{$pktid} = $to;
	    next;
	}

	$from = $entry[2];
	$type = $entry[4];
	$size = $entry[5];
	$packet_source{$pktid} = $to;
    }
    
    if ($outfile[$to] eq "") {
	if ($outfile[$to] eq "") {
	    $outfile[$to] = $fh++;
	    open($outfile[$to], ">tp$to.log") or die "couldn't open tp$to.log";
	    push @trace_list, $to;
	    $trace_type[$to] = "$type";
	    $p_time[$to] = 0.0;
	    $p_data[$to] = 0;
	    printf { $outfile[$to] } "0.0 0\n";
	}
    }

    while ($time > $p_time[$to] + $granularity) {
	$p_time[$to] += $granularity;
	printf { $outfile[$to] } "%08.4f %i\n", $p_time[$to], $p_data[$to] / $granularity;
	$p_data[$to] = 0.0;
    }

    $p_data[$to] += $size;
}
close(infile);

foreach $to (@trace_list) {
    while ($time >= $p_time[$to] + $granularity) { # fill rest with 0
	$p_time[$to] += $granularity;
	printf { $outfile[$to] } "%08.4f %i\n", $p_time[$to], $p_data[$to] / $granularity;
	$p_data[$to] = 0;
    }
    close($outfile[$to]);
}

open(cmd, ">cmd.tmp");
print cmd "set term post color solid 20\n";
print cmd "set output \"out.ps\"\n";
print cmd "set key top left\n";
print cmd "set xlabel \"Time (s)\"\n";
print cmd "set xrange [0:$time]\n";
print cmd "set yrange [0:]\n";
print cmd "set ylabel \"Throughput (KBit/s)\"\n";
print cmd "plot ";
$nr = 0;
@trace_list = @ARGV if (@ARGV > 0);
foreach $node (@trace_list) {
    if ($nr > 0) {
	print cmd ", ";
    }
    print cmd "\"tp$node.log\" u 1:(\$2*8/1000) t \"$trace_type[$node]\" w l ", ++$nr;
}
print cmd "\n";
close(cmd);
system "gnuplot cmd.tmp; rm -f cmd.tmp";
