#python
"""This is a generic script for drawing multiple histograms for the data contained in the input file. It takes in a text file with n lines (separated by ' '). Makes a histogram of each line and plots the analytic pdf over it. The first entry in each line should be the labels for this line. 
Each line in the file is plotted as a separate histogram. 

Input: 	file

Flags:	-h heading between  - DOESN'T wORK""
	-s save in the following folder
	-noline - no fitting line """


import os 
import sys
import pylab
import numpy as np
import matplotlib.mlab as mlab

from statlib import stats as st

DATA = '/proj/aesop/data_lists'
PROC = '/proj/aesop/proc'

def read_file(file):
	'''Reads the data file'''
	data = {}
	names = []
	for line in file:
		if line == '\n' or len(line) == 0:
			continue
		vals = line.split(' ')
		print len(vals)
		data[vals[0]] = []
		names.append(vals[0])
		for v in vals[1:]:
			data[vals[0]].append(float(v))
	return (data, names)
	
	
def check_quotes(alist, string):
    '''obsolete function for -h flag which doesn't work'''
    for m in range(1, len(alist)):
		string = string + ' ' +alist[m]
		if '"' in alist[m]:
			return string

def read_arglist(arglist):
	'''Reads arglist'''
	save = 'no'
	h = ''
	fold = ''
	nl = 'yes'
	f = arglist[0]
	for n in range(1, len(arglist)):
		if arglist[n]  ==  '-h':
			h = check_quotes(arglist[n+1:], arglist[n+1])
		elif arglist[n]  ==  '-s':		
			save = 'yes'
			fold = arglist[n+1]
			if os.path.exists(fold) == False:
				os.mkdir(fold)
		elif arglist[n] == '-noline':
			nl = 'no'
	return (f, h, save, fold, nl)
		
def draw_hist(data, names, h, save, file, nl):
	pylab.figure()
	pylab.subplots_adjust(hspace = 0.001)
	x_all = []
	for l in data.keys():
		x_all.extend(data[l])
	ax1 = pylab.subplot(len(data.keys()), 1, 1)
	n, bins, patches = pylab.hist(x_all, 50, normed = 1)
	bincenters  =  0.5*(bins[1:]+bins[:-1])
	y  =  mlab.normpdf( bincenters, np.mean(x_all), np.std(x_all))
	pylab.plot(bincenters, y, 'r--', linewidth = 1)
	pylab.ylabel('all')
	pylab.annotate('mean = %.2f' % (np.mean(x_all)), xy = (-50, 15), xycoords = 'axes points', fontsize = 8)
	pylab.annotate('std = %.2f' % (np.std(x_all)), xy = (-50, 5), xycoords = 'axes points', fontsize = 8)
	i = 1
	for l in names:
		ax2 = pylab.subplot(len(data.keys()), 1, i, sharex = ax1)
		x = data[l]
		n, bins, patches = pylab.hist(x, 20, normed = 1)
		bincenters  =  0.5*(bins[1:]+bins[:-1])
		y  =  mlab.normpdf( bincenters, np.mean(x), np.std(x))
		if nl == 'yes':
			pylab.plot(bincenters, y, 'r--', linewidth = 1)
		pylab.ylabel(l, rotation = 'horizontal')
		pylab.annotate('mean = %.2f' % (np.mean(x)), xy = (-50, -10), xycoords = 'axes points', fontsize = 8)
		pylab.annotate('std = %.2f' % (np.std(x)), xy = (-50, -20), xycoords = 'axes points', fontsize = 8)
		pylab.annotate('n = %d' % (len(x)), xy = (-50, -30), xycoords = 'axes points', fontsize = 8)
		pylab.yticks([], [])
		if not i == len(data.keys()):
			for tl in ax2.get_xticklabels():
				tl.set_visible(False)
			
		i += 1
	if save == 'yes':
		pylab.savefig(file)
	else:
		pylab.show()	
	
if __name__  ==  '__main__':
	arglist = sys.argv[1:]
	(f, h, save, fold, nl)  =  read_arglist(arglist)
	print 'Drawing histogram for %s, to be saved in %s' % (f, fold)
	output = os.path.join(fold, '_'.join([os.path.basename(f), 'histo'])+'.png')
	print output
	(data, names) = read_file(open(f, 'r'))
	draw_hist(data, names, h, save, output, nl)	


