#!/usr/bin/perl -w

use strict;

my @dirs = ("async0-mode-1", "async0-mode0", "async0-mode1",
            "async1-mode-1", "async1-mode0", "async1-mode1");

my $dataset = 0;
my $basedir = "throughput-result";
$basedir = $ARGV[0] if @ARGV== 1;
my $load_threshold = 20;
for my $dir (@dirs) {
  my @loads = ();

  {
    open LH, "< $basedir/data-$dir/sub-ethload.log" or next; # die "can't open $basedir/data-$dir/sub-ethload.log";
    my @curload = ();
    while (<LH>) {
      next unless /^r +([0-9.]+).*\( *(\d+)/;
      push @curload, $2 if $1 > $load_threshold;
      if (@curload && $1 < $load_threshold) {
        push @loads, median (@curload);
        @curload = ();
      }
    }
    push @loads, median (@curload) if @curload;
    close LH;
  }

  open FH, "< $basedir/data-$dir/sub.log" or next; # die "can't open $basedir/data-$dir/sub.log";
  print "\n\n" if $dataset++;
  print "# mode $dir\n";
  print "# payloadsize rate[samples/s] appl.bandwidth[Mb/s] raw.bandwidth[Mb/s]\n";
  my $psz;
  my @rate = ();
  while (<FH>) {
    next unless /Payload size: ([0-9]+).*Transfer rate: ([0-9.]+)/;
    my $psz_cur = $1; my $rate_cur = $2;
    $psz = $psz_cur unless defined $psz;
    if ($psz != $psz_cur) {
      my $load = shift @loads;
      my $rate = median (@rate);
      printf "%d %f %f %f\n", $psz, $rate, $rate * (8 + $psz) / 125e3, $load / 125e3;
      @rate = ();
    }
    $psz = $psz_cur;
    push @rate, ($rate_cur + 0.0);
  }
  my $load = shift @loads;
  my $rate = median (@rate);
  printf "%d %f %f %f\n", $psz, $rate, $rate * (8 + $psz) / 125e3, $load / 125e3;
  close FH;
}

sub median {
  my @xs = sort { $a <=> $b } @_;
  return (@xs % 2) ? $xs[(@xs - 1) / 2] : ($xs[@xs/2 - 1] + $xs[@xs/2]) / 2;
}

