#!/usr/local/bin/perl

$i = 0;
@totaltime = ();
@totalstate = ();
@state = ();
@total = ();

$batches = $ARGV[0];

while (<STDIN>) {
  if (/simulation time (.+)$/) {
    $times[$i] = $1;
  }
  if (/^txnc1 \|\| txnc2 .+ time (.+)$/) {
    $state[$i++] = $1;
  }
}

print STDERR "$i markers found\n";

$inc = int ($i / $batches);

$k = $batches;
$c = 0;
$marker = $i - 1;

for ($j=$i-1; $j >= 0; $j--) {
#  $totaltime[$k] += $times[$j];
#  $totalstate[$k] += $state[$j];
  $c++;
  if ($c >= $inc) {
    $totaltime[$k] = $times[$marker] - $times[$j];
    $totalstate[$k] = $state[$marker] - $state[$j];
    print "batch $k total $totaltime[$k] state $totalstate[$k]\n";
    $k--;
    $c = 0;
    $marker = $j;
  }
}

$bmean = 0;
for ($j = 0; $j < $batches; $j++) {
  $bmean += $totalstate[$j+1];
}
$bmean = $bmean / $batches;

print "mean of state residence is $bmean\n";

$smean = 0;
for ($j = 0; $j < $batches; $j++) {
  $smean += $totaltime[$j+1];
}
$smean = $smean / $batches;

print "mean of overall residence is $smean\n";

$vari = 0;
for ($j = 0; $j < $batches; $j++) {
  $vari += ($bmean - $totalstate[$j+1])**2;
}
$vari = $vari / $batches;

print "variance of state residence is $vari\n";
print "standard deviation of state residence is ".sqrt($vari)."\n";
