#!/usr/bin/perl -w
#
# $Id: makeplot,v 1.3 2003/03/03 11:39:38 kjc Exp $
#
#  usage:
#	makeplot [-3D] <plotdatafile> [<pngfile>]
#
#  example: to create a plot graph, sample.png
#	aguri -P -yM -xd agr_files     > plotdata
#	makeplot plotdata | gnuplot > sample.png
#
#     to create a 3D plot
#	makeplot -3D plotdata | gnuplot > sample3D.png
#
umask(002);
$pngfile = "";
$plot_3d = 0;

if ($#ARGV < 0)  { die "plotdata file not specified!"; }
$datafile = shift @ARGV;
if ($datafile eq "-3D") {
    $plot_3d = 1;
    $datafile = shift @ARGV;
}
if ($#ARGV >= 0) {
    $pngfile = shift @ARGV;
}

sub putpreamble {
    print <<EOF;
set terminal png color small
#set size 0.75, 0.75
set key below Left
set xlabel "Time"
set ylabel "Traffic (Mbps)"
#set yrange [0:100]	# to fix y-scale
set xdata time
set timefmt "%Y/%m/%d:%H:%M:%S"
set format x "%H:%M\\n%m/%d"
EOF
}

sub putpreamble3d {
    print <<EOF;
set terminal png color small
#set size 0.75, 0.75
set key below Left
set xlabel "ranking"
set ylabel "Time"
set zlabel "Traffic (Mbps)"
#set zrange [0:100]	# to fix z-scale
#set view 60,30,1,1
set ticslevel 0
set ydata time
set timefmt "%Y/%m/%d:%H:%M:%S"
set format y "%H:%M %m/%d"
EOF
}

open(DATA, "< $datafile") || die $!;
while(<DATA>) {
    # detect type
    if (/^#\[(.*)\]/) {
	$title = $1;
	next;
    }
    # read names for legends, and then, output gnuplot command
    if (/^#time/) {
	chop;
	@legends = split;
	$entries = $#legends + 1;
	print "set title \'$title\'\n";
	if ($pngfile ne "") {
	    print "set output \"$pngfile\"\n";
	}
	if ($plot_3d == 0) {
	    # create 2D plot
	    putpreamble();
	    for ($i = 1; $i < $entries; $i++) {
		if ($i == 1) {
		    print "plot ";
		} else {
		    print ", ";
		}
		print "\"$datafile\" using 1:", $i+1, " t \'$legends[$i]\' w lines";
	    }
	} else {
	    # create 3D plot
	    putpreamble3d();
	    for ($i = 1; $i < $entries; $i++) {
		if ($i == 1) {
		    print "splot ";
		} else {
		    print ", ";
		}
		print "\"$datafile\" using (", $i-1, "):1:", $i+1, " t \'$legends[$i]\' w impulses";
	    }
	}
	print "\n";
	last;
    }
}
close(DATA);
exit 0;
