#!/bin/nawk -f

# Break up output from adaptWl into multiple gnuplot files
#  This version is to be used to graph multiple focal points

BEGIN {
    graphOn = 0;
    graphStarted = 0;
    if (prefix == "") {
	prefix = FILENAME;
	print "setting prefix to", prefix;
    }
}

(index($0, "--- focal point") > 0) {
    graphStarted = 1;
    focalPoint = $0;
    sub("^--- focal point #","", focalPoint);
    sub(",.*$","",focalPoint);
    focalPointMB = $7 " " $8;
    print "got to the focal point #", focalPoint, ", starting to graph";
    print "focalPointMB = " focalPointMB;
}

(graphStarted && graphOn == 1 && $1 != "dra") {
    # print $0 >> nameData ;
    if ($1 == "dae") {
	dasOn = 0;
	print "" >> nameData;
    }

    if ($1 == "das") {
	dasOn = 1;
    } else if (dasOn == 1) {
	xData = $1;
	yData = $2;
	sub (";", "", yData);
	print xData, yData >> nameData;
    }
}

(graphStarted && $1 == "gti") {
    title = $2;
    if (title == "") {
	print "error: null title";
	exit(1);
    }
    if (titlePlotted[focalPoint,title] == 1) {
	#print "error: already plotted", title;
	print "turning graphStarted -> 0";
	graphStarted = 0;
	#exit(1);
    } else {
	graphOn = 1;
	titlePlotted[focalPoint,title] = 1;
	nameData = prefix "_f" focalPoint "_" title ".gnudata";
	name = prefix "_f" focalPoint "_" title;
	# print $0 > nameData ;
	print "plotting", name;

	# create the gnuplot command file
	gnuCommand = name ".gnucommand"
	print "set data style linespoints" > gnuCommand;
	print "set autoscale x" >> gnuCommand;
	print "set terminal postscript" >> gnuCommand;
	if (length(name) > 47) {
	    print "** WARNING: file name (" name ".ps) is ";
	    print "**          " length(name)+3 " characters long.  This is longer than gnuplot will handle";
	    print "**          (max of 50 characters)."
	    print "**          Try cd'ing to the directory with the output";
	    print "**          file and running gnuplotWl from there.";
	    print "**          ABORTING gnuplotWl";
	    exit(1);
	}
	printf("set output \"%s.ps\"\n", name) >> gnuCommand;
	printf("set title \"%s (%s)\"\n", name, focalPointMB) >> gnuCommand;
	printf("set xlabel \"%s\"\n", title) >> gnuCommand;
	printf("set ylabel \"throughput (MB/s)\"\n") >> gnuCommand;
	if (title == "sizeMean") {
	    print "set logscale x" >> gnuCommand;
	}
	printf("plot \"%s\"\n", nameData) >> gnuCommand;
	system ("rm -f " nameData);
    }
}

(graphStarted && $1 == "dra") {
    graphOn = 0;
    #print "dra " prefix title ".grn" >> (prefix title ".gg") ;
    ## print "dra " name ".grn" >> nameData ;
    #system("ggraph " namegg);
    system("gnuplot " gnuCommand);
    close nameData;
    close gnuCommand;
}
