#!/usr/bin/perl

use strict;
use warnings;

my $dir = $ARGV[0];
die "Usage: makeplot <pgbench-dash-l-output-dir>\n" if !defined $dir;

if (! -f "$dir/summary")
{
	opendir(DIR, $dir) || die "opendir: $!";
	my @f = grep { /^pgbench/ } readdir(DIR);
	closedir(DIR);

	my $min = 0;
	for my $f (@f)
	{
		open(F, '<', "$dir/$f") || die "open $dir/$f: $!";
		my $l = <F>;
		my @l = split /\s+/, $l;
		$min = $l[4] if $min == 0 || $l[4] < $min;
		close(F);
	}

	my @tps;

	open(S, '>', "$dir/summary") || die "open $dir/summary: $!";

	for my $f (@f)
	{
		open(F, '<', "$dir/$f") || die "open $dir/$f: $!";
		while (my $l = <F>)
		{
			my @l = split /\s+/, $l;
			die "line has other than 6 fields" if @l != 6;
			printf S "%s %.3f\n", $l[4] - $min, $l[2] / 1000;
			$tps[$l[4] - $min]++;
		}
		close(F);
	}

	close(S);

	open(T, '>', "$dir/tps") || die "open $dir/tps: $!";

	for (my $i = 0; $i < @tps; ++$i)
	{
		printf T "%s %s\n", $i, defined $tps[$i] ? $tps[$i] : 0;
	}

	close(T);
}

open(P, '>', "$dir/plot");
print P <<EOM;
set title "pgbench latency, scale factor 300, 1800 seconds, 32-core AMD Opteron 6128\\nbranch $dir"
set xlabel "Time (s)"
set ylabel "Latency (ms)"
set xrange [ 0:1810 ]
set grid
set nokey
set terminal png
set output 'latency-$dir.png'
plot '$dir/summary' using 1:2
EOM

open(P, '>', "$dir/plot.tps");
print P <<EOM;
set title "pgbench tps, scale factor 300, 1800 seconds, 32-core AMD Opteron 6128\\nbranch $dir"
set xlabel "Time (s)"
set ylabel "Transactions Completed"
set xrange [ 0:1810 ]
set grid
set nokey
set terminal png
set output 'tps-$dir.png'
plot '$dir/tps' using 1:2
EOM

system "gnuplot $dir/plot";
system "gnuplot $dir/plot.tps";
