#!/usr/bin/perl -w

# perl -e 'for(0..100) { print "5.333,"; }'

use strict;

foreach(@ARGV) {
    open FF, $_ or die "Can't open $_: $!";
    my(@file) = (<FF>);
    my($file) = join("",@file);
    &process($_,$file);
    close FF;
}

sub process {
    my($fn, $file) = @_;
    my(@file);
    @file = split(/sync\n/,$file);
    my(@errors, @errors_flex, @sinces, $name);
    my($var_targ) = 0;
    my($first_error) = 0;
    
    foreach(@file) {
	my($errors, $streams, $mean);
	if(/^Total errors: (\d+)/m) {
	    $errors = $1;
	} else {
	    next;
	    # die "Can't find Total errors in file.";
	}
	if(/^Options: block_size: \d+, num_streams: (\d+)/m) {
	    $streams = $1;
	} else {
	    die "Can't find options.";
	}
	if(/^Results: .\/(\w+)/m) {
	    $name = $1;
	} else {
	    die "Can't find name.";
	}
	if(/^Mean: (\d+\.\d+)/m) {
	    $mean = $1;
	}

	next if($mean >= 16000/3);
	# print "$streams\t$errors\n";
	$errors[$streams] = $errors;
	$errors_flex[$streams] = 0;
	my(@lines) = split(/\n/, $_);
	foreach (@lines) {
	    if(/^Since (\d+): (\d+)/) {
		my($block,$since) = ($1, $2);
		if($since >= 16000/3) {
		    ++$errors_flex[$streams];
		}
		
	    }
	}
	# next if($mean >= 15900/3);
	next if ($errors_flex[$streams] > 1 and $first_error);
	if($errors_flex[$streams] >0) { 
	    $first_error = 1; 
	}
	$var_targ = $streams;
	@sinces = ();
	foreach (@lines) {
	    if(/^Since (\d+): (\d+)/) {
		my($block,$since) = ($1, $2);
		$sinces[$block] = $since;
	    }
	}
    }
    my($ctr) = 0;
    while(1) {
	last if (defined($errors[++$ctr]));
	$errors[$ctr] = 0;
    }
    for($#errors..67) {
	$errors[$_] = 100;
    }
    $ctr = 0;
    while(1) {
	last if (defined($errors_flex[++$ctr]));
	$errors_flex[$ctr] = 0;
    }
    for($#errors_flex..67) {
	$errors_flex[$_] = 100;
    }

    shift @errors;
    shift @errors_flex;
    my($best_flex) = 0;
    foreach(@errors_flex) {
	if($_ < 2) {
	    $best_flex++;
	}
    }
    my($best) = 0;
    foreach(@errors) {
	if($_ < 2) {
	    $best++;
	}
    }
    if($fn =~ /bsd/ms) { $name = "bsd$name"; }
    print "$name"."_best = [ $best ]\n";
    print "$name"."_fbest = [ $best_flex ]\n";
    print "$name"."_var = [ $var_targ ]\n";
    print "$name"."_errors = [ ".join(",", @errors)." ]\n";
    print "$name"."_ferr = [ ".join(",", @errors_flex)." ]\n";
    shift @sinces;
    @sinces = map { $_ / 1000 } @sinces;
    print "$name"."_since = [ ".join(", ", @sinces)." ]\n";
}
