#! /usr/bin/perl

use strict;

sub parse_data_file {
    my $filename = shift;
    my $result = {};
    local(*FH);

    $result->{NAME} = $filename;
    open(FH, "<$filename") || return undef;

    while (<FH>) {
        if ($_ =~ m/^attribute\s+"([^"]*)"\s+"([^"]*)"/) {
            $result->{ATTRIBUTES}{$1} = $2;
        } elsif ($_ =~ m/^timer\s+([0-9]+)\s+([0-9.]+)\s([0-9]+)\s"([^"]*)"/) {
            $result->{TIMER}[$1] = $2;
            $result->{TIMER_NAME}[$1] = $4;
        }
    }
    close(FH);

    return $result;
}

my $data = {};

foreach (<*.log>) {
    my $name = $_;
    my $res = parse_data_file($name);

    if (defined($res)) {
        my $iterations = $res->{ATTRIBUTES}{iterations};

        push(@{$data->{$iterations}}, $res);
        
    } else {
        die ("Unable to parse $name\n");
    }
}

foreach (keys %{$data}) {
    my @records = @{$data->{$_}};

    local(*GNUPLOT);
    print "$_ -> " . scalar(@records) . "\n";

    open (GNUPLOT, "|/usr/bin/gnuplot");
    #open (GNUPLOT, ">>foo");
    select GNUPLOT;
    $|=1;

    print GNUPLOT "set terminal png\n";
    print GNUPLOT "set output \"$_.png\"\n";
    print GNUPLOT "set title \"$_ iterations\"\n";
    print GNUPLOT "set logscale x\n";
    print GNUPLOT "set xlabel \"Message Size (Resource Properties)\"\n";
    print GNUPLOT "set ylabel \"Time for $_ iterations (seconds)\"\n";
    print GNUPLOT "plot ";
    print GNUPLOT join(', ', map { "'-' title \"$_->{NAME}\" with lines" } @records);
    print GNUPLOT "\n";

    foreach (@records) {
        my $record = $_;

        for (my $i = 0; $i < scalar(@{$record->{TIMER}}); $i++) {
            my $size = (split(/\s+/, $record->{TIMER_NAME}[$i]))[0];
            print "$size $record->{TIMER}[$i]\n";
        }
        print "e\n";
    }
    close(GNUPLOT);
}
