#!/usr/bin/env python                                                                                                                                                                                      
import math
import os, shlex
import subprocess
import glob
import shutil
import json
import ROOT
ROOT.gROOT.SetBatch(True)
from collections import OrderedDict
import CMS_lumi, tdrstyle
from optparse import OptionParser
from array import array
import json
import numpy as np
parser = OptionParser()
parser.add_option("--inputCard", type="string", dest="inputCard", help="Full path where the datacard is")
parser.add_option("--outPath", type="string", dest="outPath", help="Full path to store plot and ws")
parser.add_option("--Info", type="string", dest="analysisInfo", help="analysis info e.g. 3l_1tau_2016_nonResLO_SM")
parser.add_option("--log", action='store_true',dest="logy", default=False)
parser.add_option("--NLO", action='store_true',dest="NLO", default=False)
parser.add_option("--paper", action='store_true',dest="paper", default=False)
parser.add_option("--isCR", action='store_true',dest="isCR", default=False)
parser.add_option("--isAdd", action='store_true',dest="isAdd", default=False)
parser.add_option("--skipCombine", action='store_true',dest="skipCombine", default=False)
parser.add_option("--Bins", type="string", dest="Bins", help="Bin in datacard to plot")
parser.add_option("--sigDesc", type="string", dest="sigDesc", help="Additional sig description")
parser.add_option("--sigQuant", type="int", dest="sigQuant", help="Where to blind", default = -1)
parser.add_option("--sigScale", type="int", dest="sigScale", help="Signal scale for linear plots", default = -1)
parser.add_option("--post", action='store_true',dest="post", default=False)
parser.add_option("--largeRatio", action='store_true',dest="largeRatio", default=False)
parser.add_option("--unblindSig", action='store_true',dest="unblindSig", default=False)
parser.add_option("--ratio", action='store_true',dest="ratio", default=False)
parser.add_option("--xlabel", type="string", dest="xlabel", help="x axis label", default = None)
parser.add_option("--ylabel", type="string", dest="ylabel", help="y axis label", default = None)
parser.add_option("--lumilabel", type="string", dest="lumilabel", help="lumi label", default = None)
parser.add_option("--binfile", type="string", dest="binfile", help="File with original binning ", default = None)
parser.add_option("--binshapes", action='store_true',dest="binshapes", default=False)
parser.add_option("--fitfile", type="string", dest="fitfile", help="Fitdiagnostics file, sets skipCombine to true ", default = None)
parser.add_option("--minY", type="float", dest="minY", help="min y for log", default = 0.001)
parser.add_option("--maxY", type="float", dest="maxY", help="max y for log", default = -1)
parser.add_option("--maxX", type="float", dest="maxX", help="max x for log", default = -1)
parser.add_option("--ratioMax", type="float", dest="ratioMax", help="ratio max", default = -1)
parser.add_option("--ratioMin", type="float", dest="ratioMin", help="ratio min", default = -9999)
parser.add_option("--perGeV", type="float", dest="perGeV", help="divide by binWidth", default = -1)
parser.add_option("--unblind", action='store_true',dest="unblind", default=False)
parser.add_option("--hideSig", action='store_true',dest="hideSig", default=False)
parser.add_option("--quad", action='store_true',dest="quad", default=False)
parser.add_option("--preliminary", action='store_true',dest="preliminary", default=False)
parser.add_option("--channel", type="string", dest="channel", help="channel label", default = None)
parser.add_option("--prelText", type="string", dest="prelText", help="preliminary Text", default = "Preliminary")
parser.add_option("--fakesText", type="string", dest="fakesText", help="fakes Text", default = "\\text{Misid. }\\ell/\\tau_{h}")
parser.add_option("--extra", type="string", dest="extra", help="extra label", default = None)
(options, args) = parser.parse_args()
inputCard = options.inputCard   
outPath = options.outPath
ylabel = options.ylabel
logy = options.logy
fakesText=options.fakesText
signaldesc = options.sigDesc
Bins = options.Bins.split(":")
analysisInfo = options.analysisInfo
skipCombine=options.skipCombine 
isNLO = options.NLO
isCR = options.isCR
isAdd = options.isAdd
minY = options.minY
maxY = options.maxY
maxX = options.maxX
perGeV = options.perGeV
ratioMin_ = options.ratioMin 
ratioMax_ = options.ratioMax 
sigQuant = options.sigQuant
sigScale = options.sigScale
post = options.post
largeRatio = options.largeRatio
paper = options.paper
unblindSig = options.unblindSig
ratio = options.ratio
xlabel = options.xlabel
ylabel = options.ylabel
lumilabel = options.lumilabel
binfile = options.binfile
binshapes = options.binshapes
fitfile = options.fitfile
unblind = options.unblind
hideSig = options.hideSig
quad = options.quad
preliminary = options.preliminary
channel = options.channel
prelText = options.prelText
extra = options.extra
if fitfile: skipCombine = True

def transferHist(templatehist, hist, shapes=False):
    temphist = hist.Clone()
    temphist.Reset()
    edges = []
    for i in range(templatehist.GetNbinsX()+1):
        edges.append(hist.GetBinLowEdge(i+1))
    edges= np.array(edges)
    temphist = temphist.Rebin(len(edges)-1,temphist.GetName(),edges)
    if shapes:
        temphist = templatehist.Clone()
    for i in range(templatehist.GetNbinsX()+1):
        temphist.SetBinContent(i,hist.GetBinContent(i))
        temphist.SetBinError(i,hist.GetBinError(i))
    temphist.SetBinContent(templatehist.GetNbinsX()+1, hist.GetBinContent(hist.GetNbinsX()+1))
    temphist.SetBinError(templatehist.GetNbinsX()+1, hist.GetBinError(hist.GetNbinsX()+1))
    temphist.SetLineColor(hist.GetLineColor())
    temphist.SetFillColor(hist.GetFillColor())
    temphist.SetFillStyle(hist.GetFillStyle())
    temphist.SetLineWidth(hist.GetLineWidth())
    temphist.SetTitle(hist.GetTitle())
    temphist.SetName(hist.GetName())
    return temphist

oldhist = None
olddata = None
if binfile:
    oldfile = ROOT.TFile(binfile)
    oldhist = oldfile.Get("data_obs").Clone()
    if isCR or unblind:
        olddata = oldfile.Get("data_obs").Clone()
    oldhist.Reset()
# Bin = "HH_3l_1tau"                                                                                                                                                                                        
# logy = True                                                                                                                                                                                               
# ylabel="hh-multilepton 3l1tau (2016)"                                                                                                                                                                     
# signaldesc= "SM (1pb)"                                                                                                                                                                                    
# outPath=options.outPath                                                                                                                                                                                   


commands = []
wspath="%s/ws_%s.root"%(outPath,analysisInfo)
commands.append("text2workspace.py %s -o %s -m 125"%(inputCard,wspath))
commands.append("combineTool.py -M FitDiagnostics -d %s --skipBOnlyFit --saveShapes  --saveWithUncertainties --cminDefaultMinimizerType Minuit2 --cminDefaultMinimizerStrategy 0 --cminFallbackAlgo Minuit2,0:1.0 -n _%s -m 125 -v 5"%(wspath, analysisInfo))
commands.append("mv fitDiagnostics_%s.root %s"%(analysisInfo, outPath))
commands.append("mv higgsCombine_%s.FitDiagnostics.*.root %s"%(analysisInfo, outPath))
if not skipCombine:
    for command in commands:
        print command
        p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        for line in p.stdout.readlines():
            print line.rstrip("\n")
        print 'done'
        retval = p.wait()


if not fitfile: fitfile = ROOT.TFile("%s/fitDiagnostics_%s.root"%(outPath, analysisInfo))
else: fitfile = ROOT.TFile(fitfile)
print fitfile
postfitshapefolder=fitfile.Get("shapes_fit_s")
if isAdd:
    postfitshapefolder=fitfile.Get("shapes_fit_b")
prefitshapefolder=fitfile.Get("shapes_prefit")
prefitshapes= prefitshapefolder.Get(Bins[0])
postfitshapes= postfitshapefolder.Get(Bins[0])
print prefitshapes
yieldDict = {}
total = None
data = None
if post:
    if not isCR: 
        total = postfitshapes.Get("total_background")
    else:
        total = postfitshapes.Get("total")
    data = postfitshapes.Get("data")
else:
    if not isCR: 
        total = prefitshapes.Get("total_background")
    else: 
        total = prefitshapes.Get("total")
    data = prefitshapes.Get("data")
total.SetLineColor(0)
total.SetFillColor(0)
err = ROOT.TH1D("err", "err", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
ZZ  = ROOT.TH1D("ZZ", "ZZ", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
ZZ.SetLineColor(ROOT.kRed)
ZZ.SetFillColor(ROOT.kRed)
ggZZ  = ROOT.TH1D("ggZZ", "ggZZ", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
ggZZ.SetLineColor(634)
ggZZ.SetFillColor(634)
qqZZ  = ROOT.TH1D("qqZZ", "qqZZ", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
qqZZ.SetLineColor(ROOT.kOrange)
qqZZ.SetFillColor(ROOT.kOrange)
WZ  = ROOT.TH1D("WZ", "WZ", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
WZ.SetFillColor(ROOT.kBlue-6)
WZ.SetLineColor(ROOT.kBlue-6)
WZ.SetFillStyle(3002)
singleH  = ROOT.TH1D("singleH", "singleH", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
singleH.SetLineColor(ROOT.kOrange+1)
singleH.SetFillColor(ROOT.kOrange+1)
TT  = ROOT.TH1D("TT", "TT", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
TT.SetFillColor(16)
TT.SetLineColor(16)
Other  = ROOT.TH1D("Other", "Other", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
Other.SetLineColor(851)
Other.SetFillColor(851)
DY  = ROOT.TH1D("DY", "DY", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
DY.SetLineColor(395)
DY.SetFillColor(395)
Flips  = ROOT.TH1D("Flips", "Flips", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
Flips.SetLineColor(1)
Flips.SetFillColor(1)
Flips.SetFillStyle(3254)
Convs  = ROOT.TH1D("Convs", "Convs", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
Convs.SetLineColor(ROOT.kGreen-3)
Convs.SetFillColor(ROOT.kGreen-3)
#Convs.SetFillStyle(3005)
TTX  = ROOT.TH1D("TTX", "TTX", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
TTX.SetLineColor(823)
TTX.SetFillColor(823)
W  = ROOT.TH1D("W", "W", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
W.SetLineColor(822)
W.SetFillColor(822)
WW  = ROOT.TH1D("WW", "WW", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
WW.SetLineColor(436)
WW.SetFillColor(436)
signal_4v  = ROOT.TH1D("HH_WWWW", "HH_WWWW", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
signal_4v.SetLineColor(ROOT.kBlue)
signal_4v.SetLineWidth(4)
signal_4v.SetFillColor(0)
signal_2v2t  = ROOT.TH1D("HH_WWTT", "HH_WWTT", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
signal_2v2t.SetLineColor(ROOT.kRed)
signal_2v2t.SetFillColor(0)
signal_2v2t.SetLineWidth(4)
signal_4t  = ROOT.TH1D("HH_TTTT", "HH_TTTT", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
signal_4t.SetLineColor(ROOT.kYellow)
signal_4t.SetFillColor(0)
signal_4t.SetLineWidth(4)
signal  = ROOT.TH1D("HH", "HH", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
#signal.SetLineColor(1)
signal.SetLineColor(ROOT.kMagenta+3)
signal.SetFillColor(0)
signal.SetLineStyle(9)
signal.SetLineWidth(6)
signal_ggHH_WWWW  = ROOT.TH1D("ggHH_WWWW", "ggHH_WWWW", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
signal_qqHH_WWWW  = ROOT.TH1D("qqHH_WWWW", "qqHH_WWWW", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
signal_ggHH_TTTT  = ROOT.TH1D("ggHH_TTTT", "ggHH_TTTT", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
signal_qqHH_TTTT  = ROOT.TH1D("qqHH_TTTT", "qqHH_TTTT", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
signal_ggHH_WWTT  = ROOT.TH1D("ggHH_WWTT", "ggHH_WWTT", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
signal_qqHH_WWTT  = ROOT.TH1D("qqHH_WWTT", "qqHH_WWTT", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())

data_fakes  = ROOT.TH1D("data_fakes", "data_fakes", total.GetNbinsX(),total.GetXaxis().GetXmin(),total.GetXaxis().GetXmax())
data_fakes.SetLineColor(2)
data_fakes.SetFillColor(2)
data_fakes.SetFillStyle(3245)
error = ROOT.Double(0.)
for Bin in Bins:
    bgshapes = None
    sgshapes = None
    if post:
        bgshapes = postfitshapefolder.Get(Bin)
    else: 
        bgshapes = prefitshapefolder.Get(Bin)
    if not unblindSig:
        sgshapes = prefitshapefolder.Get(Bin)
    else: 
        sgshapes = postfitshapefolder.Get(Bin)
    if Bin is not Bins[0]:
        data2 = bgshapes.Get("data")
        transferdatax = []
        transferdataexl = []
        transferdataexh = []
        transferdatay = []
        transferdataeyl = []
        transferdataeyh= []
        print data
        for i in range(total.GetNbinsX()):
            x = ROOT.Double()
            y = ROOT.Double()
            x2 = ROOT.Double()
            y2= ROOT.Double()
            data.GetPoint(i,x,y)
            data2.GetPoint(i,x2,y2)
            transferdatax.append(ROOT.Double(total.GetBinCenter(i+1)))
            transferdataexl.append(ROOT.Double(total.GetBinWidth(i+1))/2)
            transferdataexh.append(ROOT.Double(total.GetBinWidth(i+1))/2)
            transferdatay.append(y+y2)
            transferdataeyh.append(ROOT.Math.gamma_quantile_c( (1-0.68)/2, 1+(y+y2), 1) - (y+y2))
            if (y+y2)>0:
                transferdataeyl.append((y+y2) -ROOT.Math.gamma_quantile( (1-0.68)/2, (y+y2), 1))
            else:
                transferdataeyl.append(0)
           # transferdataeyl.append(math.sqrt(data.GetErrorYlow(i)**2+data2.GetErrorYlow(i)**2))
            #transferdataeyh.append(math.sqrt(data.GetErrorYhigh(i)**2+data2.GetErrorYhigh(i)**2))
        n = len(transferdatax)
        transferdatax = array('f', transferdatax)
        transferdataexl = array('f', transferdataexl)
        transferdataexh = array('f', transferdataexh)
        transferdatay = array('f', transferdatay)
        transferdataeyl = array('f', transferdataeyl)
        transferdataeyh = array('f', transferdataeyh)
        data = ROOT.TGraphAsymmErrors(n, transferdatax, transferdatay, transferdataexl, transferdataexh, transferdataeyl, transferdataeyh)
        if not isCR: 
            total.Add(bgshapes.Get("total_background"))
        else: 
            total.Add(bgshapes.Get("total"))
    for entry in bgshapes.GetListOfKeys():
        name = entry.GetName()
        print name
        if 'total' in name:
            continue
        elif ('ggH_' in name or 'qqH_' in name or 'TTH_' in name or 'tHq_' in name or 'tHW_' in name or 'WH_' in name or 'ZH_' in name or 'ttH_' in name):
            singleH.Add(bgshapes.Get(name))
        elif ('ggHH' in name or 'qqHH' in name or 'signal' in name):
            #if (isNLO and not ('kl_1_kt_1_' in name or 'CV_1_C2V_1_kl_1_' in name)): continue
            temphist =sgshapes.Get(name)
            signal.Add(temphist)
            print name
            print "found signal"
            if '_hwwhww' in name or '_hzzhzz' in name or '_hzzhww' in name:
                signal_4v.Add(temphist)
                if 'C2V' not in name or not isNLO:
                    signal_ggHH_WWWW.Add(temphist)
                else:
                    signal_qqHH_WWWW.Add(temphist)
            if '_htthww' in name or '_htthzz'in name:
                signal_2v2t.Add(temphist)
                if 'C2V' not in name or not isNLO:
                    signal_ggHH_WWTT.Add(temphist)
                else:
                    signal_qqHH_WWTT.Add(temphist)
            if '_htthtt' in name:
                signal_4t.Add(temphist)
                if 'C2V' not in name or not isNLO:
                    signal_ggHH_TTTT.Add(temphist)
                else:
                    signal_qqHH_TTTT.Add(temphist)
            yield_ = temphist.IntegralAndError(0,-1,error)
            if temphist.GetName() not in  yieldDict.keys():
                yieldDict[temphist.GetName()]=[str(yield_),str(error)]
            else:
                newval = float(yieldDict[temphist.GetName()][0]) + yield_
                newerr = math.sqrt(error**2+float(yieldDict[temphist.GetName()][1])**2)
                yieldDict[temphist.GetName()]=[str(newval),str(newerr)]
        elif (('ggH' in name or 'qqH' in name or 'TTH' in name or 'tHq' in name or 'tHW' in name or 'WH' in name or 'ZH' in name or 'ttH' in name) and isAdd):
            singleH.Add(bgshapes.Get(name))
        elif (('ggH' in name or 'qqH' in name or 'TTH' in name or 'tHq' in name or 'tHW' in name or 'WH' in name or 'ZH' in name or 'ttH' in name) and isCR):
            Other.Add(bgshapes.Get(name))
        elif  ('ggZZ'in name or'qqZZ' in name):
            ZZ.Add(bgshapes.Get(name))
            if 'ggZZ' in name:
                ggZZ.Add(bgshapes.Get(name))
            if 'qqZZ' in name:
                qqZZ.Add(bgshapes.Get(name))
        elif ('DY' in name):
            DY.Add(bgshapes.Get(name))
        elif ('Other' in name):
            Other.Add(bgshapes.Get(name))
        elif ('Flips' in name or 'data_flips' in name or 'flips_mc' in name):
            Flips.Add(bgshapes.Get(name))
        elif ('Convs' in name):
            Convs.Add(bgshapes.Get(name))
        elif( 'TTZ' in name or "TTW" in name or 'ttZ' in name):
            TTX.Add(bgshapes.Get(name))
        elif( 'TT' in name or 'ttbar' in name):
            TT.Add(bgshapes.Get(name))
        elif ('WZ' in name):
            WZ.Add(bgshapes.Get(name))
        elif ('WW' in name):
            WW.Add(bgshapes.Get(name))
        elif ('W' in name):
            W.Add(bgshapes.Get(name))
        elif ("data_fakes"  in name):
            data_fakes.Add(bgshapes.Get(name))
        #elif ("data" in name and "data_fakes" not in name and 'data_flips' not in name):
         #   print "hello"
         #   data = bgshapes.Get(name)
print signal.Integral(), signal.GetName()
print signal_4v.Integral(), signal_4v.GetName()
print signal_2v2t.Integral(), signal_2v2t.GetName()
print signal_4t.Integral(), signal_4t.GetName()
#if isCR:
#     yieldDict["data_obs"]=[str(data.Integral()),str(0)]
if binfile:
    total = transferHist(oldhist, total,binshapes) 
    err = transferHist(oldhist, err,binshapes) 
    ZZ = transferHist(oldhist, ZZ,binshapes) 
    ggZZ = transferHist(oldhist, ggZZ,binshapes) 
    qqZZ = transferHist(oldhist, qqZZ,binshapes) 
    WZ = transferHist(oldhist, WZ,binshapes) 
    W = transferHist(oldhist, W,binshapes) 
    WW = transferHist(oldhist, WW,binshapes) 
    data_fakes = transferHist(oldhist, data_fakes,binshapes) 
    Flips = transferHist(oldhist, Flips,binshapes) 
    Convs = transferHist(oldhist, Convs,binshapes) 
    TT = transferHist(oldhist, TT,binshapes) 
    TTX = transferHist(oldhist, TTX,binshapes) 
    singleH = transferHist(oldhist, singleH,binshapes) 
    DY = transferHist(oldhist, DY,binshapes) 
    Other = transferHist(oldhist, Other,binshapes) 
    signal = transferHist(oldhist, signal,binshapes) 
    signal_4v = transferHist(oldhist, signal_4v,binshapes) 
    signal_4t = transferHist(oldhist, signal_4t,binshapes) 
    signal_2v2t = transferHist(oldhist, signal_2v2t,binshapes) 
    transferdatax = []
    transferdataexl = []
    transferdataexh = []
    transferdatay = []
    transferdataeyl = []
    transferdataeyh= []
    for i in range(oldhist.GetNbinsX()):
        x = ROOT.Double()
        y = ROOT.Double()
        data.GetPoint(i,x,y)
        if binshapes:
            transferdatax.append(ROOT.Double(oldhist.GetBinCenter(i+1)))
            transferdataexl.append(ROOT.Double(oldhist.GetBinWidth(i+1))/2)
            transferdataexh.append(ROOT.Double(oldhist.GetBinWidth(i+1))/2)
        else:            
            transferdatax.append(ROOT.Double(total.GetBinCenter(i+1)))
            transferdataexl.append(ROOT.Double(total.GetBinWidth(i+1))/2)
            transferdataexh.append(ROOT.Double(total.GetBinWidth(i+1))/2)
        transferdatay.append(y)
        transferdataeyl.append(data.GetErrorYlow(i))
        transferdataeyh.append(data.GetErrorYhigh(i))
    n = len(transferdatax)
    transferdatax = array('f', transferdatax)
    transferdataexl = array('f', transferdataexl)
    transferdataexh = array('f', transferdataexh)
    transferdatay = array('f', transferdatay)
    transferdataeyl = array('f', transferdataeyl)
    transferdataeyh = array('f', transferdataeyh)
    data = ROOT.TGraphAsymmErrors(n, transferdatax, transferdatay, transferdataexl, transferdataexh, transferdataeyl, transferdataeyh)
if (isCR or unblind) and binfile:
    yieldDict["data_obs"]=[str(olddata.Integral()),str(0)]
yield_ = total.IntegralAndError(0,-1,error)
yieldDict['totalBG']=[str(yield_),str(error)]
print 'total', yield_,error
bglist=[]
if paper:
    bglist.append(ZZ)
    bglist.append(WZ)
    bglist.append(singleH)
    bglist.append(data_fakes)
    bglist.append(Flips)
    bglist.append(Convs)
    rare = Other.Clone()
    rare.Add(DY)
    rare.Add(W)
    rare.Add(WW)
    rare.Add(TT)
    rare.Add(TTX)
    bglist.append(rare)
else:
    bglist.append(ZZ)
    bglist.append(WZ)
    bglist.append(W)
    bglist.append(WW)
    bglist.append(data_fakes)
    bglist.append(Flips)
    bglist.append(Convs)
    bglist.append(TT)
    bglist.append(TTX)
    bglist.append(singleH)
    bglist.append(DY)
    bglist.append(Other)




datax = []
dataexl = []
dataexh = []
datay = []
dataeyl = []
dataeyh= []
datay_perGeV = []
dataeyl_perGeV = []
dataeyh_perGeV= []
blindarea = data.GetN()/2
print "1111elf", data.GetN(), sigQuant
if (sigQuant >= 0):
    blindarea = min(sigQuant,data.GetN())
if unblind:
    blindarea = data.GetN()
for i in range(blindarea):
    x = ROOT.Double()
    y = ROOT.Double()
    data.GetPoint(i,x,y)
    datax.append(x)
    #dataexl.append(data.GetErrorXlow(i))
    #dataexh.append(data.GetErrorXhigh(i))
    dataexl.append(0)
    dataexh.append(0)
    datay.append(y)
    binWidth = total.GetBinWidth(total.FindBin(x))
    datay_perGeV.append(y*(perGeV/binWidth))
    if logy and y<=0 and False:
        dataeyl.append(0)
        dataeyh.append(0)
        dataeyl_perGeV.append(0)
        dataeyh_perGeV.append(0)
    else:
        dataeyl.append(data.GetErrorYlow(i))
        dataeyh.append(data.GetErrorYhigh(i))
        dataeyl_perGeV.append(data.GetErrorYlow(i)*(perGeV/binWidth))
        dataeyh_perGeV.append(data.GetErrorYhigh(i)*(perGeV/binWidth))
    
   
n = len(datax)
datax = array('f', datax)
dataexl = array('f', dataexl)
dataexh = array('f', dataexh)
datay = array('f', datay)
dataeyl = array('f', dataeyl)
dataeyh = array('f', dataeyh)
datay_perGeV = array('f', datay_perGeV)
dataeyl_perGeV = array('f', dataeyl_perGeV)
dataeyh_perGeV = array('f', dataeyh_perGeV)

data_blinded = ROOT.TGraphAsymmErrors(n, datax, datay, dataexl, dataexh, dataeyl, dataeyh)
print datay
print datay_perGeV
data_blinded_perGeV = ROOT.TGraphAsymmErrors(n, datax, datay_perGeV, dataexl, dataexh, dataeyl_perGeV, dataeyh_perGeV)

bglist = sorted(bglist, key=lambda hist: hist.Integral())
bgstack = ROOT.THStack("bgs","bgs")
if not xlabel:
    xlabel = "BDTOutput in background quantiles"
    if paper:
        xlabel = "Bin number"
    if sigQuant >= 0:
        xlabel = "BDTOutput in signal quantiles"
if not ylabel:
    ylabel = "\\text{Events}"
if perGeV>0:
    ylabel = "\\text{Events / %s GeV}"%int(perGeV)
    if perGeV<1:
        ylabel = "\\text{Events / %s }"%perGeV
bgstack.SetTitle(";%s; %s"%(xlabel,ylabel))
for hist in bglist:
    if hist.Integral()>0.:
        yield_ = hist.IntegralAndError(0,-1,error)
        yieldDict[hist.GetName()]=[str(yield_),str(error)]
        print hist.GetName(), hist.Integral(), error
        if perGeV>0:
            for i in range(hist.GetNbinsX()):
                t_cont = hist.GetBinContent(i+1)
                t_err =  hist.GetBinError(i+1)
                f = perGeV/hist.GetBinWidth(i+1)
                hist.SetBinContent(i+1,f*t_cont)
                hist.SetBinError(i+1,f*t_err)
        bgstack.Add(hist)
        err.Add(hist)
       


yield_ = signal_ggHH_WWWW.IntegralAndError(0,-1,error)
yieldDict["signal_ggHH_WWWW"]=[str(yield_),str(error)]
yield_ = signal_qqHH_WWWW.IntegralAndError(0,-1,error)
yieldDict["signal_qqHH_WWWW"]=[str(yield_),str(error)]
yield_ = signal_ggHH_WWTT.IntegralAndError(0,-1,error)
yieldDict["signal_ggHH_WWTT"]=[str(yield_),str(error)]
yield_ = signal_qqHH_WWTT.IntegralAndError(0,-1,error)
yieldDict["signal_qqHH_WWTT"]=[str(yield_),str(error)]
yield_ = signal_ggHH_TTTT.IntegralAndError(0,-1,error)
yieldDict["signal_ggHH_TTTT"]=[str(yield_),str(error)]
yield_ = signal_qqHH_TTTT.IntegralAndError(0,-1,error)
yieldDict["signal_qqHH_TTTT"]=[str(yield_),str(error)]

print total.Integral()
print signal.Integral(), signal.GetName()
print signal_4v.Integral(), signal_4v.GetName()
print signal_2v2t.Integral(), signal_2v2t.GetName()
print signal_4t.Integral(), signal_4t.GetName()
W = 800
H  = 600
T = 0.08*H
B = 0.12*H
L = 0.12*W
R = 0.04*W
c = ROOT.TCanvas("c","c",100,100,W,H)
if quad:
    c = ROOT.TCanvas("c","c",100,100,W,W)
c.SetFillColor(0)
c.SetBorderMode(0)
c.SetFrameFillStyle(0)
c.SetFrameBorderMode(0)
c.SetLeftMargin( L/W )
c.SetRightMargin( 1.1*R/W )
c.SetTopMargin( T/H )
c.SetBottomMargin( B/H )
if quad:
    c.SetBottomMargin( B/H )
c.SetTickx(0)
c.SetTicky(0)
#c.SetGrid()
c.cd()


CMS_lumi.cmsText = "CMS"
CMS_lumi.extraText = "       "+prelText
if "Progress" in prelText:
    CMS_lumi.extraText = "    "+prelText
if not preliminary:
    CMS_lumi.extraText = ""
CMS_lumi.cmsTextSize = 0.65
if "Sup" in CMS_lumi.extraText or "Progress" in prelText:
    CMS_lumi.extraTextSize = 0.8 * CMS_lumi.extraTextSize
CMS_lumi.outOfFrame = True
tdrstyle.setTDRStyle()
pad1 = None
pad2 = None
if ratio:
    pad1=ROOT.TPad("pad1","pad1", 0, 0.3,1,1.0)
    pad1.SetBottomMargin(0.025)
    pad1.SetTopMargin(0.1)
    pad1.SetRightMargin(1.3*0.025)
    pad1.Draw()
    c.cd()
    pad2=ROOT.TPad("pad2","pad2", 0, 0.05,1,0.3)
    pad2.SetTopMargin(0)
    pad2.SetRightMargin(1.3*0.025)
    pad2.SetBottomMargin(0.46)
    if quad:
        pad2.SetTopMargin(0.1)
        pad2.SetBottomMargin(0.45)
    pad2.Draw()
    pad1.cd()
bgstack.Draw("hist")
if maxX >0:
    bgstack.GetXaxis().SetRangeUser(0,maxX)
#bgstack.Draw("hist")
#latex = ROOT.TLatex()
latex = ROOT.TMathText()
latex.SetNDC()
latex.SetTextAngle(0)
latex.SetTextSize(1.5*latex.GetTextSize())
if 'ss' in channel and preliminary and 'tau' in channel:
    latex.SetTextSize(0.8*latex.GetTextSize())
    if "Private" in prelText or "Progress" in prelText:
        latex.SetTextSize(0.8*latex.GetTextSize())
#latex.SetTextColor(ROOT.kRed)    

latex.SetTextAlign(23)
if channel:
    if not preliminary:
        latex.DrawMathText(0.49,0.975, channel)
    else:
        if 'ss' in channel and 'tau' in channel:
            if "Private" in prelText or "Progress" in prelText:
                latex.DrawMathText(0.56,0.955, channel)
            else:
                latex.DrawMathText(0.56,0.965, channel)
        else:
            latex.DrawMathText(0.56,0.975, channel)
else:
    if post:
       if unblindSig and not hideSig:
           latex.DrawMathText(0.6,0.55, "postFit")
       else:
           latex.DrawMathText(0.6,0.55, "postFit")
    else:
       if not hideSig:
           latex.DrawMathText(0.6,0.55, "preFit")
       else:
           latex.DrawMathText(0.6,0.55, "preFit (no sig)")
if extra:
    latex2 = ROOT.TMathText()
    latex2.SetNDC()
    latex2.SetTextAlign(23)
    latex2.SetTextAngle(0)
    latex2.SetTextSize(1.5*latex2.GetTextSize()*0.8)
    latex2.DrawMathText(0.6,0.525, extra)
# if channel:
#     if isCR:
#         latex.DrawLatex(0.85,0.7, channel)
#     else:
#         latex.DrawLatex(0.925,0.52, channel)
# else:
#     if post:
#        if unblindSig and not hideSig:
#            latex.DrawLatex(0.6,0.55, "postFit")
#        else:
#            latex.DrawLatex(0.6,0.55, "postFit")
#     else:
#        if not hideSig:
#            latex.DrawLatex(0.6,0.55, "preFit")
#        else:
#            latex.DrawLatex(0.6,0.55, "preFit (no sig)")

bgstack.GetYaxis().SetTitleOffset(1.7)
bgstack.GetYaxis().SetTitleFont(43)
bgstack.GetYaxis().SetLabelSize(30)
bgstack.GetYaxis().SetLabelOffset(0.015)
bgstack.GetYaxis().SetLabelFont(43)
bgstack.GetXaxis().SetTitleSize(35)
#bgstack.GetYaxis().SetTitleSize(1.15*bgstack.GetYaxis().GetTitleSize())
bgstack.GetYaxis().SetTitleSize(35)
if total.GetNbinsX()< 30 and not binfile:
    for i in range(total.GetNbinsX()):
        bgstack.GetXaxis().SetBinLabel(bgstack.GetXaxis().FindBin(i),"bin"+str(i))
if logy:
    bgstack.SetMinimum(minY)
    bgstack.SetMaximum(750*max(total.GetMaximum(),np.max(datay)))
    if ratio:
        pad1.SetLogy()
    else:
        c.SetLogy()
else:
    bgstack.SetMaximum(max(7.5,max(3*max(total.GetMaximum(),np.max(datay)),3) )+2) 
if isCR:
    bgstack.SetMaximum(max(7.5,max(1.75*max(total.GetMaximum(),np.max(datay)),3) )+1) 
if maxY > -1:
    bgstack.SetMaximum(maxY)
if signal.Integral()>0 and not hideSig:
    sig1 = signal.Clone()
    sig2 = signal_4v.Clone()
    sig3 = signal_2v2t.Clone()
    sig4 = signal_4t.Clone()
    if sigScale > 0.:
        sig1.Scale(sigScale)
        sig2.Scale(sigScale)
        sig3.Scale(sigScale)
        sig4.Scale(sigScale)
    yield_ = sig2.IntegralAndError(0,-1,error)
    yieldDict["signal_4vscaled"]=[str(yield_),str(error)]
    yield_ = sig3.IntegralAndError(0,-1,error)
    yieldDict["signal_2v2tscaled"]=[str(yield_),str(error)]
    yield_ = sig4.IntegralAndError(0,-1,error)
    yieldDict["signal_4tscaled"]=[str(yield_),str(error)]
    if perGeV>0:
        for hist in [sig1,sig2,sig3,sig4]:
            for i in range(hist.GetNbinsX()):
                t_cont = hist.GetBinContent(i+1)
                t_err =  hist.GetBinError(i+1)
                f = perGeV/hist.GetBinWidth(i+1)
                hist.SetBinContent(i+1,f*t_cont)
                hist.SetBinError(i+1,f*t_err)

    sig1.SetLineColor(ROOT.kMagenta+3)
    sig1.SetFillColor(0)
    sig1.SetLineStyle(9)
    sig1.SetLineWidth(6)

    sig1.Draw("histsame")
    #sig2.Draw("histsame")
    #sig3.Draw("histsame")
    #sig4.Draw("histsame")
#err.SetFillColorAlpha(ROOT.kBlack,0.6);
err.SetFillColor(14)
err.SetFillStyle(3344);
#err.SetFillColor(ROOT.kBlack)
err.SetMarkerStyle(0);
err.SetLineColor(0);
err.Draw("E2SAME")
data_blinded.SetMarkerStyle(20)
#data_blinded.SetMarkerSize(1.2)
data_blinded.SetMarkerSize(1.5)
data_blinded.SetLineWidth(3)
data_blinded_perGeV.SetMarkerStyle(20)
#data_blinded_perGeV.SetMarkerSize(1.2)
data_blinded_perGeV.SetMarkerSize(1.5)
data_blinded_perGeV.SetLineWidth(3)

if (not logy) and largeRatio:
    #data_blinded.SetMarkerSize(1.5)
    data_blinded.SetMarkerSize(1.75)
    #data_blinded_perGeV.SetMarkerSize(1.5)
    data_blinded_perGeV.SetMarkerSize(1.75)
if perGeV>0:
    data_blinded_perGeV.Draw("e1psame")
else:
    data_blinded.Draw("e1psame")
#data_blinded.Draw("e1psame")
c.Update()
boxminX = total.GetBinLowEdge(blindarea+1)
boxmaxX = total.GetBinLowEdge(total.GetNbinsX()) + total.GetBinWidth(total.GetNbinsX())
boxmaxY = c.GetUymax()
if ratio: boxmaxY = pad1.GetUymax()
box = ROOT.TBox(boxminX,0.,boxmaxX, boxmaxY)
if logy:
    box = ROOT.TBox(boxminX,0.,boxmaxX, ROOT.TMath.Power(10,boxmaxY))
box.SetFillColorAlpha(ROOT.kGray, 0.5)
box.Draw("same")
legend = ROOT.TLegend(0.2,0.58,0.93,0.88)
legend.SetNColumns(3)
legend.SetFillStyle(0)
legend.SetTextFont(42)
legend.SetBorderSize(0)
for i in range(len(bglist)):
    hist = bglist[len(bglist)-1-i]
    if hist.Integral()>0:
        tempname = hist.GetName()
        #if "fakes" in tempname: tempname = "Fakes"
        #if "fakes" in tempname: tempname = "Misid. leptons"
        if "fakes" in tempname: tempname = fakesText
        #if "singleH" in tempname: tempname = "Single Higgs"
        if "singleH" in tempname: tempname = "Single H"
        if "Convs" in tempname: tempname = "Conversions"
        #if "Other" in tempname: tempname = "Other backgrounds"
        if "Other" in tempname: tempname = "Other bkg."
        if "Flips" in tempname: tempname = "Charge Misid."
        legend.AddEntry(hist, tempname,"F")
legend.AddEntry(data_blinded, "Data", "E1P")
legend.AddEntry(err, "Uncertainty", "F")
if not unblind:
    legend.AddEntry(box, "Blinded", "F")
if signal.Integral()>0 and not hideSig:
    if paper:
        signal.SetLineStyle(9)
        if "res" in signaldesc:
            legend.AddEntry(signal, '#Chi#rightarrow HH (1 pb)', "L")
        elif "eft" in signaldesc:
            legend.AddEntry(signal, 'HH (1 pb)', "L")
        elif "ggHH" in signaldesc:
            legend.AddEntry(signal, "%s"%(signaldesc), "L")
        elif isAdd:
            legend.AddEntry(signal, "%s"%(signaldesc), "L")
        else:
            legend.AddEntry(signal, 'SM HH #times 30', "L")
    else:
        if "res" in signaldesc:
            legend.AddEntry(signal, '#Chi#rightarrow HH (1 pb)', "L")
        elif "eft" in signaldesc:
            legend.AddEntry(signal, 'HH (1 pb)', "L")
        else:
            legend.AddEntry(signal, "%s"%(signaldesc), "L")
legend.Draw()
# legend = ROOT.TLegend(0.2,0.6,0.65,0.9)
# if paper:
#     legend = ROOT.TLegend(0.18,0.58,0.755,0.88)
# if signal.Integral()<=0. or hideSig:
#     legend = ROOT.TLegend(0.2,0.6,0.9,0.9)
#     legend.SetNColumns(4)
# else:
#     legend.SetNColumns(3)
# legend.SetFillStyle(0);                                                                                                                                                                                    legend.SetTextFont(42);                                                                                                                                                                                    legend.SetBorderSize(0); 
# for i in range(len(bglist)):
#     hist = bglist[len(bglist)-1-i]
#     if hist.Integral()>0:
#         tempname = hist.GetName()
#         if "fakes" in tempname: tempname = "Fakes"
#         if "singleH" in tempname: tempname = "Single Higgs"
#         if "Convs" in tempname: tempname = "Conversions"
#         if "Other" in tempname: tempname = "Other backgrounds"
#         legend.AddEntry(hist, tempname,"F")
# legend.AddEntry(err, "Uncertainty", "F")
# legend.AddEntry(data_blinded, "Data", "E1P")
# if not unblind:
#     legend.AddEntry(box, "Blinded", "F")
# legend.Draw()


# legend_sig = ROOT.TLegend(0.65,0.6,0.95,0.9)
# if paper:
#     legend_sig = ROOT.TLegend(0.755,0.58,0.98,0.88)
# legend_sig.SetFillStyle(0);
# legend_sig.SetTextFont(42); 
# legend_sig.SetBorderSize(0); 
# legend_sig.AddEntry(signal_4v, "%s"%(signaldesc)+ ' HH#rightarrow 4V', "L")
# legend_sig.AddEntry(signal_2v2t, "%s"%(signaldesc)+ ' HH#rightarrow 2V2#tau', "L")
# legend_sig.AddEntry(signal_4t, "%s"%(signaldesc)+ ' HH#rightarrow 4#tau', "L")
# legend_sig.AddEntry(signal, "%s"%(signaldesc)+ ' Total HH', "L")
# if signal.Integral()>0 and not hideSig:
#     legend_sig.Draw()
data_ratio = None
if ratio:
    pad2.cd()
    r_datax = []
    r_dataexl = []
    r_dataexh = []
    r_datay = []
    r_dataeyl = []
    r_dataeyh= []
    r_datay_perGeV = []
    r_dataeyl_perGeV = []
    r_dataeyh_perGeV= []

    for i in range(data.GetN()):
        x = ROOT.Double()
        y = ROOT.Double()
        data.GetPoint(i,x,y)
        div = ROOT.Double(err.GetBinContent(err.FindBin(x)))
        div = max(div,0.00001)
        print div, y, y/div
        r_datax.append(x)
        #r_dataexl.append(data.GetErrorXlow(i))
        #r_dataexh.append(data.GetErrorXhigh(i))
        r_dataexl.append(0)
        r_dataexh.append(0)
        r_datay.append(y/div)
        r_dataeyl.append(data.GetErrorYlow(i)/div)
        r_dataeyh.append(data.GetErrorYhigh(i)/div)
        binWidth = total.GetBinWidth(total.FindBin(x))
        r_datay_perGeV.append(y*(perGeV/binWidth)/div)
        r_dataeyl_perGeV.append(data.GetErrorYlow(i)*(perGeV/binWidth)/div)
        r_dataeyh_perGeV.append(data.GetErrorYhigh(i)*(perGeV/binWidth)/div)

    r_n = len(datax)
    r_datax = array('f', r_datax)
    r_dataexl = array('f', r_dataexl)
    r_dataexh = array('f', r_dataexh)
    r_datay = array('f', r_datay)
    r_dataeyl = array('f', r_dataeyl)
    r_dataeyh = array('f', r_dataeyh)
    r_datay_perGeV = array('f', r_datay_perGeV)
    r_dataeyl_perGeV = array('f', r_dataeyl_perGeV)
    r_dataeyh_perGeV = array('f', r_dataeyh_perGeV)

    data_ratio = ROOT.TGraphAsymmErrors(r_n, r_datax, r_datay, r_dataexl, r_dataexh, r_dataeyl, r_dataeyh)
    data_ratio_perGeV = ROOT.TGraphAsymmErrors(r_n, r_datax, r_datay_perGeV, r_dataexl, r_dataexh, r_dataeyl_perGeV, r_dataeyh_perGeV)
    err_ratio = err.Clone()
    #for i in range(err_ratio.GetNbinsX()):
    #    err_ratio.SetBinContent(i+1,1)
    #    err_ratio.SetBinError(i+1, err.GetBinError(i+1)/err.GetBinContent(i+1))
    err_ratio.Divide(err)
    err_ratio.Draw("E2")
    err_ratio.GetYaxis().SetTitleSize(35)
    err_ratio.GetYaxis().SetTitleFont(43)
    err_ratio.GetYaxis().SetTitleOffset(1.35)
    err_ratio.GetYaxis().SetLabelSize(30)
    err_ratio.GetYaxis().SetLabelFont(43)
    err_ratio.GetXaxis().SetTitleSize(35)
    err_ratio.GetXaxis().SetTitleFont(43)
    err_ratio.GetXaxis().SetTitleOffset(4.2)
    err_ratio.GetXaxis().SetLabelSize(30)
    err_ratio.GetXaxis().SetLabelFont(43)
    err_ratio.GetYaxis().SetNdivisions(505)
    err_ratio.GetXaxis().SetLabelOffset(0.025)
    err_ratio.GetYaxis().SetLabelOffset(0.015)
    if paper and not isCR:
        for i in range(err_ratio.GetNbinsX()+1):
            if err_ratio.GetNbinsX()>15:
                if i%5 is 0 or i is 1:
                    err_ratio.GetXaxis().SetBinLabel(i,str(i))
            else:
                err_ratio.GetXaxis().SetBinLabel(i,str(i))
            
    # if largeRatio:
    #     err_ratio.SetMaximum(2)
    #     err_ratio.SetMinimum(0)
    #     #if len(Bins)>2:
    #     #    err_ratio.SetMaximum(1.5)
    #     #    err_ratio.SetMinimum(0.5)
    # else:
    #     err_ratio.SetMaximum(1.5)
    #     err_ratio.SetMinimum(0.5)
    #     if len(Bins)>2:
    #         err_ratio.SetMaximum(1.25)
    #         err_ratio.SetMinimum(0.75)
    # if "1l_3tau" in Bin or "0l_4tau" in Bin:
    #         err_ratio.SetMaximum(3)
    #         err_ratio.SetMinimum(-1)
    #ratioMax = min(1.5,max(1.7*err_ratio.GetMaximum(),1.3*max(r_datay)))
    #ratioMin = max(0.5, 1-abs(ratioMax-1))
    #if logy and min(r_datay) == 0:
    #    ratioMin = 0.5
    ratioMax=2
    ratioMin=0
    err_ratio.GetYaxis().SetNdivisions(503)
    if largeRatio:
        ratioMax=2.5
        ratioMin=-0.5
    if isCR:
        ratioMin=0.7
        ratioMax = 1.3
    if logy:
        ratioMin=0.3
        ratioMax=1.7
        if largeRatio:
            ratioMax=2.5
            ratioMin=-0.5
        if "ss" in channel:
            ratioMin=0.7
            ratioMax = 1.3
    if ratioMin_ > -9999: ratioMin = ratioMin_
    if ratioMax_ > 0.1: ratioMax = ratioMax_
    err_ratio.SetMaximum(ratioMax)
    err_ratio.SetMinimum(ratioMin)
    err_ratio.SetTitle(";%s;\\frac{\\text{Data}}{\\text{Expectation}}"%(bgstack.GetXaxis().GetTitle()))
    #err_ratio.SetTitle(";%s;"%(bgstack.GetXaxis().GetTitle()))
    err_ratio.GetYaxis().CenterTitle()
    if maxX >0:
        err_ratio.GetXaxis().SetRangeUser(0,maxX)
    err_ratio.Draw("E2")
    # else:
    line = ROOT.TF1("line","1", err.GetXaxis().GetXmin(), err.GetXaxis().GetXmax())
    #     line.SetMaximum(1.3)
    #     line.SetMinimum(0.7)
    #     line.GetYaxis().SetTitleSize(20)
    #     line.GetYaxis().SetTitleFont(43)
    #     line.GetYaxis().SetTitleOffset(1.)
    #     line.GetYaxis().SetLabelSize(15)
    #     line.GetYaxis().SetLabelFont(43)
    #     line.GetXaxis().SetTitleSize(20)
    #     line.GetXaxis().SetTitleFont(43)
    #     line.GetXaxis().SetTitleOffset(4)
    #     line.GetXaxis().SetLabelSize(15)
    #     line.GetXaxis().SetLabelFont(43)
    #     line.GetYaxis().SetNdivisions(505)
    #     line.SetTitle(";%s;Data/MC"%(bgstack.GetXaxis().GetTitle()))
    line.SetLineColor(ROOT.kRed)
    line.SetLineWidth(3)
    line.Draw("same")
    bgstack.GetXaxis().SetTitleSize(0)
    bgstack.GetXaxis().SetLabelSize(0)
    data_ratio.SetMarkerStyle(20)
    #data_ratio.SetMarkerSize(1.2)
    data_ratio.SetMarkerSize(1.5)
    data_ratio_perGeV.SetMarkerStyle(20)
    #data_ratio_perGeV.SetMarkerSize(1.2)
    data_ratio_perGeV.SetMarkerSize(1.5)
    if (not logy) and largeRatio:
        #data_ratio.SetMarkerSize(1.5)
        data_ratio.SetMarkerSize(1.75)
        #data_ratio_perGeV.SetMarkerSize(1.5)
        data_ratio_perGeV.SetMarkerSize(1.75)
    data_ratio.SetLineWidth(3)
    data_ratio_perGeV.SetLineWidth(3)
    drawoption="E1P0"
    if perGeV>0:
        data_ratio_perGeV.Draw(drawoption)
    else:
        data_ratio.Draw(drawoption)
    if unblindSig and unblind and not hideSig and ((not isCR) or isAdd):
        signal_pBG = signal.Clone()
        signal_pBG.Add(err)
        signal_pBG.Divide(err)
        signal_pBG.Draw("histsame")
    box2 = None
    # if "1l_3tau" in Bin or "0l_4tau" in Bin:
    #         box2 = ROOT.TBox(boxminX,-1.,boxmaxX, 3.)
    # elif largeRatio:
    #     if len(Bins)<3:
    #         box2 = ROOT.TBox(boxminX,0.,boxmaxX, 2.)
    #     else:
    #         box2 = ROOT.TBox(boxminX,0.,boxmaxX, 2.)
    # else:
    #     if len(Bins)<3:
    #         box2 = ROOT.TBox(boxminX,0.5,boxmaxX, 1.5)
    #     else:
    #         box2 = ROOT.TBox(boxminX,0.75,boxmaxX, 1.25)
    box2 = ROOT.TBox(boxminX,ratioMin,boxmaxX, ratioMax)
    box2.SetFillColorAlpha(ROOT.kGray, 0.5)
    box2.Draw("same")


CMS_lumi.lumi_sqrtS = lumilabel
if ratio:
    CMS_lumi.CMS_lumi(pad1,0,0)
else:
    CMS_lumi.CMS_lumi(c,0,0)
#ROOT.gPad.SetTicks(1,1)
outname = outPath + "/%s_preFit.pdf"%(analysisInfo )
if logy:
    outname = outPath + "/%s_preFit_log.pdf"%(analysisInfo )
if ratio:
    outname =outname.replace('.pdf','_ratio.pdf')
if post:
    outname =outname.replace('pre','post')
    print 'post!!!!'
c.SaveAs(outname)
c.SaveAs(outname.replace('.pdf','.root'))
c.SaveAs(outname.replace('.pdf','.png'))
c.SaveAs(outname.replace('.pdf','.eps'))
c.SetGrayscale()
c.SaveAs(outname.replace('.pdf','_grayscale.pdf'))
c.SaveAs(outname.replace('.pdf','_grayscale.root'))
c.SaveAs(outname.replace('.pdf','_grayscale.png'))
c.SaveAs(outname.replace('.pdf','_grayscale.eps'))
yieldjson = json.dumps(yieldDict)
with open(outname.replace('pdf','json'), 'w') as outfile:
    json.dump(yieldjson, outfile)


