#!/usr/bin/env python3

import os
import sys
import subprocess

from bwparser import BandwidthParser, JansenBandwidthParser

# Plot the bandwidth files using gnuplot

if __name__ == '__main__':
    if len(sys.argv) != 2:
        sys.stderr.write("Usage: outputdir\n")
        sys.exit(1)

    # set some defaults
    bandwidth_file = os.getenv('BW_FILE')
    output_dir = sys.argv[1]
    output_file = output_dir + "/bw_dist.pdf"

    # calculate invariants
    bw_parser = BandwidthParser(bw_file=bandwidth_file)
    true_avg = bw_parser.get_average()

    jansen_parser = JansenBandwidthParser(bw_file=bandwidth_file)

    # Create dat file
    with open("%s-jansen.dat" % bandwidth_file, "w") as datout:
        for i in range(1,101):
            netscale = i/100
            jansen_parser.set_scale(netscale)
            datout.write("%s %s\n" % \
                    (netscale, jansen_parser.get_average()))
        datout.close()

    # Build plot
    gpcode = """set terminal pdf font "DejaVuSans,14" size 5,2.25
    set output '%s'
    set title 'Generated Distribution for %s'
    set key out
    set arrow from 1, graph 0 to 1
    set xlabel "Scale"
    set ylabel "Average Bandwidth"
    set xtics 0.1
    plot """ % (output_file, bandwidth_file)

    gpcode += "'%s-jansen.dat' using 1:2 with lines title 'Bandwidth'" % (bandwidth_file)


    gp = subprocess.Popen(['gnuplot', '-'], stdin=subprocess.PIPE)
    gp.communicate(gpcode.encode('ascii'))
