#!/usr/bin/env python2

import os, subprocess

def listtofile(listing, file):
	fd = open(file, 'r')
	for i in listing:
		fd.write(i+"\n")
	fd.close()

def makeGraphs(graphs, graphtitle = "Title", xlabel = "Number of Parts", ylabel = "Time needed for calculation"):
	gendir = "stats/generated/"
	subprocess.call(["mkdir", "-p", gendir])
	p = subprocess.Popen(['gnuplot'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
	# now do the plots
	for graphfile in graphs:
		# set output 'filename'
		p.stdin.write("set terminal png font arial 8 #size 600,300\n")
		p.stdin.write("set grid\n")
		p.stdin.write("set datafile separator ';'\n")
		p.stdin.write("set title 'Timing of each "+graphtitle+"'\n")
		p.stdin.write("set xlabel '"+xlabel+"'\n")
		p.stdin.write("set ylabel '"+ylabel+"'\n")
		p.stdin.write("set output '"+gendir+graphfile+"'\n")
		# plot 'filename' using 1:2 title 'algorithm' with lines, 'filename2' using 1:2 title 'algo2' with lines
		plots = []
		for title, file, cols in graphs[graphfile]:
			plots.append("'"+file+"' using "+cols+" title '"+title+"' with lines")
		plotcommand = ", ".join(plots)
		#print gendir+graphfile
		p.stdin.write("plot "+plotcommand+"\n")
	p.communicate()[0]
	p.stdin.close()

statsdir = 'stats/raw/'
runs = os.listdir(statsdir)
#print runs

gendir = "stats/generated/"
graphs = []
outpng = 'merge.png'
subprocess.call(["mkdir", "-p", gendir])
for i in runs:
	runfiles = os.listdir(statsdir+i)
#	print runfiles
	for file in runfiles:
#		print "File: %s%s/%s" % (statsdir, i, file)
		splitfilename = file.split('.')
		dict = {}
		dict['arrsize'] = splitfilename[1]
		graphs.append((splitfilename[1], statsdir+i+'/'+file, '1:2'))

makeGraphs({outpng: graphs}, "merge")
