#!/usr/bin/python
# -*- coding: iso-8859-15 -*-

import os,sys
# import getopt
##maybe it's supposed to be sys.argv[:] ... maybe
tmpargv = sys.argv
sys.argv = [ '-n' ]
from ROOT import *
sys.argv = tmpargv

# import psyco
# psyco.full()

# from time import sleep
# from optparse import OptionParser

# from ROOT_Tools import RootHandler
# from CommandLineMod import CommandLine



if __name__ == "__main__":

	gStyle.SetTitleBorderSize	( 0			)   # duh
	# gStyle.SetTitleBorderSize	( 1			)
	gStyle.SetPadBorderMode		( 0			)
	gStyle.SetOptStat			( 111111	)	# Good standard stats display.
	gStyle.SetOptFit			( 1111		)	# Display fit info if available.
	# gStyle.SetMarkerStyle		( 24		)	# Open circle.
	gStyle.SetOptTitle			( 1			)	# Display histogram titles.
	gStyle.SetCanvasColor		( 10		)	# Background color (white)
	gStyle.SetPadColor			( 10		)	# Background color (white)
	gStyle.SetFillColor			( 10		)	# Background color (white)
	# gStyle.SetHistFillColor		( 10		)	# Background color (white)
	gStyle.SetFrameFillColor	( 10		)	# Background color (white)
	gStyle.SetStatColor			( 10		)	# Background color (white)
	gStyle.SetTextFont			( 132			)

	gStyle.SetPadLeftMargin		(0.12)
	gStyle.SetPadBottomMargin	(0.12)
	gStyle.SetPadTopMargin		(0.07)
	gStyle.SetPadRightMargin	(0.04)

	gStyle.SetTitleFillColor	( 10		)	# Background color (white)
	gStyle.SetTitleFontSize		( 0.08		)	# Title Font Size
	gStyle.SetTitleX			( 0.10		)	# Title box width
	gStyle.SetTitleW			( 0.50		)	# Title box width
	gStyle.SetTitleH			( 0.09		)	# Title box width

	gStyle.SetStatX				( 0.95		)	# Statistic box width
	gStyle.SetStatW				( 0.2		)	# Statistic box width
	gStyle.SetStatBorderSize	( 1			)
	gStyle.SetLegendBorderSize	( 1			)
	gStyle.SetPalette			( 1			)	# Nicer colour scale for 2D histograms.
	gStyle.SetPaperSize			( 20., 24.	)
	gStyle.SetHistLineWidth		( 1			)
	
	gStyle.SetLabelFont(132)
	gStyle.SetLabelFont(132,"X")
	gStyle.SetLabelFont(132,"Y")
	gStyle.SetLabelFont(132,"Z")
	gStyle.SetLabelFont(132,"T")
	gStyle.SetTitleFont(132)
	gStyle.SetTitleFont(132,"X")
	gStyle.SetTitleFont(132,"Y")
	gStyle.SetTitleFont(132,"Z")
	gStyle.SetTitleFont(132,"T")
	gStyle.SetLabelSize(0.04)
	gStyle.SetLabelSize(0.04,"X")
	gStyle.SetLabelSize(0.04,"Y")
	gStyle.SetLabelSize(0.04,"Z")
	gStyle.SetLabelSize(0.04,"T")
	gStyle.SetTitleSize(0.04   )
	gStyle.SetTitleSize(0.04,"X")
	gStyle.SetTitleSize(0.04,"Y")
	gStyle.SetTitleSize(0.04,"Z")
	gStyle.SetTitleSize(0.04,"T")
	gStyle.SetTextFont(132)
	gStyle.SetStatFont(132)

	gROOT.SetBatch()
	gROOT.ForceStyle()

	# No Stats !
	gStyle.SetOptStat			( 0	)	# Good standard stats display.
	gStyle.SetOptFit			( 0	)	# Display fit info if available.

	gStyle.SetTitleW			( 0.70		)	# Title box width

	# # Using the diff plot:
	# gStyle.SetPaperSize(17,19)
	# gStyle.SetCanvasDefW(900)  # Defaults
	# gStyle.SetCanvasDefH(1100)  # Defaults

	gStyle.SetPaperSize(13,13)
	gStyle.SetCanvasDefW(700)  # Defaults
	gStyle.SetCanvasDefH(700)  # Defaults

	# We can have many files in input
	# FileList	= ['../../../5/pic/OutsideMat_source/sum583-1_2-1_clk.root','../../../5/pic/OutsideMat_source/sum543-1-1_aroseclk.root']
	FileList	= ['../../../5/pic/OutsideMat_source/sum584-1_2-1_clk.root','../../../5/pic/OutsideMat_source/sum84-9-1_clk.root']
	

	HistName 	= 'PCtof_Vs_WinType'
	OutputFile	= ['../OutsideMat_s543_s583_dn.eps']
	F=[]

	NormHist	= 'MuLastPCut/MuLastP_after'

	Canv = TCanvas()
	# Leg = TLegend(0.38, 0.35,0.72,0.5)
	Leg  = TLegend(0.68, 0.75,0.98,0.98)
	Leg2 = TLegend(0.6, 0.34,0.95,0.39)

	#MinX = -100.
	#MaxX = 100.
	# MinX = -0.049
	# MaxX = 0.049

	MinY = -2000
	MaxY = 73000

	# Title	= 'TDC time versus TDC width, wire 12;Width [ns];Hit time [ns]'
	Title	= ';PC time of flight [ns];Count'
	LegName = ['Data','MC','(Data - MC) / MC']
	t=0

	H = []
	Hist2D = []
	Norm = []
	# H = [TH1D(),TH1D(),TH1D(),TH1D()]

	Canv.cd()

	MainPad    = TPad("MainPad","MainPad", 0., 0.4, 1., 1.)
	# MainPad.SetLogy()
	MainPad.Draw()

	DiffPad   = TPad("DiffPad", "DiffPad", 0., 0.0, 1., 0.4)
	DiffPad.Draw()

	Rebin = 5

	WTypes = [7,14] # Upstream
	# WTypes = [8,15]

	Sum = 0

	for i,f in enumerate(FileList):
		F.append( TFile(f) )
		Hist2D.append(F[i].Get(HistName))

		Tmp_Hist	= Hist2D[i].ProjectionY(f+'_wtype'+str(WTypes[0]), WTypes[0]+1, WTypes[0]+1)
		H.append( Hist2D[i].ProjectionY(f+'_wtype'+str(WTypes[0])+'_'+str(WTypes[1]),  WTypes[1]+1, WTypes[1]+1))
		H[i].Add(Tmp_Hist);
		H[i].Rebin(Rebin);
		H[i].Sumw2();

		Norm.append(F[i].Get(NormHist).GetEntries())

		MainPad.cd()
		MainPad.SetBottomMargin	(0.0)
		# MainPad.SetGrid(1,3)
		# gPad.SetLogY()
		if ( i == 0):
			# CommInteg = H[0].Integral()
			CommInteg = 1e6
			H[i].SetLineColor(4)
			H[i].SetLineWidth(1)
			H[i].SetMarkerColor(4)
			H[i].SetMarkerStyle(4)
			H[i].SetMarkerSize(0.7)
			H[i].Scale(CommInteg/Norm[i])
			H[i].Draw('E')
			# H[i].SetLabelSize(0)
			H[i].SetTitle(Title)
			# H[i].SetAxisRange(MinX,MaxX,'X')
			H[i].SetTitleOffset(1.7,'Y')
			# H[i].SetAxisRange(MinY,MaxY,'Y')
			# H.SetLineWidth(1)
			# H[i].SetTitleSize(0.06,"Y")
			# H[i].SetTitleOffset( 0.9, 'X')
			H[i].SetTitleOffset( 1.5, 'Y')
			# H.Fit('pol1', "Q","", 20.0, 150.0)
			# H.GetFunction('pol1').SetLineWidth(1)
			# Hdiff = H[i].Clone()
			Hdiff = TH1D("PercDiff",H[i].GetTitle(), H[i].GetNbinsX(), H[i].GetXaxis().GetXmin(), H[i].GetXaxis().GetXmax())

		else:
			H[i].SetLineColor(2)
			H[i].SetMarkerColor(2)
			# Htmp[t].SetLineWidth(1)
			H[i].SetMarkerStyle(5)
			H[i].SetMarkerSize(0.7)
			#H[i].Scale(1/H[i].Integral())
			#H[i].Scale(2000000/H[i].Integral())
			H[i].Scale(CommInteg/Norm[i])
			#H[i].Scale(H[0].Integral()/H[i].Integral())
			H[i].Draw('sameE')

			# print 'Val = ',H[0].GetBinContent(0),H[1].GetBinContent(0)
			for j in range(1,Hdiff.GetNbinsX()):
				if ( H[0].GetBinContent(j) != 0 and H[1].GetBinContent(j) != 0 ):
					# Val = ( H[0].GetBinContent(j) - H[1].GetBinContent(j)) / H[1].GetBinContent(j)
					# Err = ( H[0].GetBinContent(j)/H[1].GetBinContent(j)) * sqrt( ( H[0].GetBinError(j) * H[0].GetBinError(j) / (H[0].GetBinContent(j)*H[0].GetBinContent(j))) + ( H[1].GetBinError(j) * H[1].GetBinError(j) / (H[1].GetBinContent(j)*H[1].GetBinContent(j))))
					Val = H[0].GetBinContent(j) - H[1].GetBinContent(j)
					Err = sqrt( ( H[0].GetBinError(j) * H[0].GetBinError(j) ) + ( H[1].GetBinError(j) * H[1].GetBinError(j) ))
				else:
					Val = 0
					Err = 0
				# print Val,Hdiff.Integral(),Sum
				Hdiff.SetBinContent(j, Val)
				Hdiff.SetBinError(j, Err)
				Sum = Sum + Val

			# Hdiff.Scale(100.)
			DiffPad.cd()
			DiffPad.SetGrid()
			Hdiff.SetTitleSize(0.07)
			Hdiff.SetTitleSize(0.07,"X")
			Hdiff.SetTitleSize(0.09,"Y")
			Hdiff.SetTitleSize(0.07,"Z")
			Hdiff.SetTitleSize(0.07,"T")
			Hdiff.SetTitleOffset(0.8,"Y")
			Hdiff.SetTitle(';PC time of flight (DS - US) [ns];Difference')
			Hdiff.SetLabelSize(0.07)
			Hdiff.SetLabelSize(0.07,"X")
			Hdiff.SetLabelSize(0.07,"Y")
			Hdiff.SetLabelSize(0.07,"Z")
			Hdiff.SetLabelSize(0.07,"T")
			DiffPad.SetTopMargin	(0.0)
			DiffPad.SetBottomMargin	(0.20)
			Hdiff.Draw('E1')
			Hdiff.SetMarkerStyle(0)
			# Hdiff.SetAxisRange(MinX,MaxX,'X')
			# Hdiff.SetAxisRange(-1000,1000,'Y')
			
		# Leg.AddEntry(H[i], LegName[i]+'  '+str(H[i].GetEntries()), 'p')
		Leg.AddEntry(H[i], LegName[i], 'p')

	# Leg2.AddEntry(Hdiff, LegName[2], 'l')

	print 'Integral = ',Sum,Hdiff.Integral()

	Canv.cd()
	Leg.Draw()
	# Leg2.Draw()
	# For eps
	Canv.Print(OutputFile[0])