#! /usr/bin/python3
import sys
import matplotlib.pyplot as plt
from math import *

def plot_from_file(ax,filename,divisor):
    # 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","C4","C5"]
    textures=["-","--"]
    #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:]])
        j = impl_range[-1].index(min(impl_range[-1]))
        impl_range[-1][j-2:] = [nan for x in impl_range[-1][j-2:]]
        if sys.argv[1] == "loglog":
            ax.loglog(impl_domain, impl_range[i], textures[i%divisor], label=impl_names[i], color=colors[i//divisor])
        else:
            ax.plot(impl_domain, impl_range[i], textures[i%divisor], label=impl_names[i], color=colors[i//divisor])
    #ax.legend(loc="upper right",fancybox=True, shadow=True)
    ax.legend(loc="best",fancybox=True, shadow=True,fontsize='small')


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

nplots=len(sys.argv)-2
fig,axs = plt.subplots(2,nplots//2,sharex=True,sharey='row')
fig.set_size_inches(10, 6, forward=True)

#axs[0][0].set(title='ChebyInterpTable')
#axs[0][1].set(title='TaylorTable')
#axs[0][2].set(title='ExactInterpTable')

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

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

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

fig.tight_layout()
plt.subplots_adjust(left=0.068, right=0.998, top=0.994,
                    bottom=0.08,wspace=0.05,hspace=0.05)
#plt.savefig(sys.argv[1].rsplit('.', maxsplit=1)[0] + '.eps', format='eps')
plt.savefig('nonuniform_mem_vs_err.eps', format='eps')
plt.show()
