import numpy as np
import matplotlib.pyplot as plt
import sys

if len(sys.argv) != 2:
	print("Wrong number of arguments.")
	print("Usage: " + sys.argv[0] + " <file>")
	sys.exit(1)

t = np.genfromtxt(sys.argv[1], names=True, delimiter=',', dtype=None)

MAX=25.0

N = len(t['Run'])
num_plots=int(np.ceil(N/MAX))

ind = np.arange(int(MAX))  # the x locations for the groups
width = 0.25       # the width of the bars

def short_name(job_name):
	n = job_name.split('_')
	return n[1][:6] + "_" + n[2][2:] + "_" + n[4][:1] + "_" + n[3]
	
plt.close('all')
fig = plt.figure()
ax=[]

expid = t['Name'][0].split('_')[0]

t['Name'] = map(short_name, t['Name'])

for plot in range(1,num_plots+1):
	ax.append(fig.add_subplot(num_plots,1, plot))
	l1=(plot-1)*MAX
	l2=plot*MAX
	if plot == num_plots:
		ind = np.arange(len(t['Queue'][l1:l2]))
	rects1 = ax[plot-1].bar(ind, t['Queue'][l1:l2], width, color='r')
	rects2 = ax[plot-1].bar(ind+width, t['Run'][l1:l2], width, color='g')
	rects3 = ax[plot-1].bar(ind+width*2, t['Wasted'][l1:l2], width, color='b')
	rects4 = ax[plot-1].bar(ind+width*3, t['Failed'][l1:l2], width, color='y')
	# ax[plot-1].set_ylabel('hours')
	ax[plot-1].set_xticks(ind+width)
	ax[plot-1].set_xticklabels( t['Name'][l1:l2], rotation='vertical')
	box = ax[plot-1].get_position()
	ax[plot-1].set_position([box.x0, box.y0, box.width * 0.8, box.height*0.8])
	ax[plot-1].set_title(expid, fontsize=20, fontweight='bold')

	
	lgd = ax[plot-1].legend( (rects1[0], rects2[0], rects3[0], rects4[0]), ('Queued (h)', 'Run (h)', 'Wasted (h)', 'Failed (#)'), loc="upper left", bbox_to_anchor=(1,1) )

fig.set_size_inches(14,num_plots*6)
#plt.tight_layout()
plt.savefig(sys.argv[1]+ '.pdf', bbox_extra_artists=(lgd,), bbox_inches='tight')
#plt.savefig('foo.pdf', bbox_inches='tight')

# plt.show()


