#! /usr/bin/python3
import sys
import matplotlib.pyplot as plt
#import matplotlib.pylab as pl
#import matplotlib.gridspec as gridspec
from math import *
#import seaborn
#seaborn.set(style='ticks')

def plot_from_file(ax,filename):
    # open file and remove newlines. readlines is okay b/c
    # the input file shouldn't be thaaaat big
    f=open(filename)
    lines = [line.strip() for line in f.readlines()]
    f.close()

    # third line has the title of each implementation
    impl_names=[name for name in lines[2].split(" ")]

    # first column defines the inputs
    impl_domain = [float(x.split(" ")[0]) for x in lines[3:]]
    #colors = ["C0", "C1", "C2", "C3"]
    #colors = ["C1", "C4", "C3", "C5"]

    # plot inputs against output column
    impl_range = []
    for i in range(len(impl_names)):
        impl_range.append([float(x.split(" ")[i+1].rstrip("s")) for x in lines[3:]])
        if sys.argv[1] == "loglog":
            ax.loglog(impl_domain, impl_range[i], '-', label=impl_names[i]) #, color=colors[i])
        else:
            ax.plot(impl_domain, impl_range[i], '-', label=impl_names[i]) #, color=colors[i])
    ax.legend(loc="best",fancybox=True, shadow=True)


if len(sys.argv) <= 2:
    print("usage:", sys.argv[0], "<loglog|plot> <filename1> <filename2> ...")
    exit()


fig, axs = plt.subplots(1,3,sharex=True,sharey=True)
fig.set_size_inches(14, 5, forward=True)

axs[1].set(xlabel='Memory usage (B)')
axs[0].set(ylabel='Error')

for ax in axs:
    ax.autoscale(enable=True, axis='x', tight=True)
    #ax.set_ylim(bottom=7*10**-16, top=1)
    ax.grid(True, which='both')

for i in range(len(sys.argv)-2):
    plot_from_file(axs[i],sys.argv[i+2])

fig.tight_layout()



#buff = 0.05
#plt.axis([-pi-2*buff,pi+2*buff,-1-buff,1+buff])
#seaborn.despine(ax=ax, offset=0)
#plt.savefig(sys.argv[1].rsplit('.', maxsplit=1)[0] + '.eps', format='eps')
plt.savefig('uniform_mem_vs_err.eps', format='eps')
plt.show()
