k1_res = json.load(jsonfile)[args.kappa_results.split(':')[1]]

masses = args.masses.split(',')
mass_dict = {}
for m in masses:
    particle = m.split(':')[0]
    mass = float(m.split(':')[1])
    mass_dict[particle] = mass

kappa_graph = ROOT.TGraphAsymmErrors(len(k1_res.keys()))

kappa_graph_fix = ROOT.TGraphAsymmErrors(1)

split = args.ratio
canv = ROOT.TCanvas(args.output, args.output)
pads = pads = plot.TwoPadSplit(0.30, 0.006, 0.006) if split else plot.OnePad()

haxis = plot.CreateAxisHist(c68, True)
haxis.GetXaxis().SetTitle('Particle mass [GeV]')
haxis.GetYaxis().SetTitle(
    '#kappa_{F}#frac{m_{F}}{v} or #sqrt{#kappa_{V}}#frac{m_{V}}{v}')
haxis.GetYaxis().SetTitleOffset(haxis.GetYaxis().GetTitleOffset() * 0.9)
haxis.SetMinimum(7E-5)
pads[0].SetLogx(True)
pads[0].SetLogy(True)
pads[0].cd()
pads[0].SetTickx(True)
pads[0].SetTicky(True)
if args.x_range is not None:
    haxis.GetXaxis().SetLimits(float(args.x_range.split(',')[0]),
                               float(args.x_range.split(',')[1]))
                          pregraph=new_gr)
    for other in other_scans:
        color = other['func'].GetLineColor()
        other['spline'] = ROOT.TSpline3("spline3", other['graph'])
        other['func'] = ROOT.TF1(
            'splinefn' + str(NAMECOUNTER), partial(Eval, other['spline']),
            other['graph'].GetX()[0],
            other['graph'].GetX()[other['graph'].GetN() - 1], 1)
        NAMECOUNTER += 1
        other['func'].SetLineColor(color)
        other['func'].SetLineWidth(2)
        # other['func'].SetLineStyle(2)
        other['graph'].SetMarkerSize(0.4)

canv = ROOT.TCanvas(args.output, args.output)
pads = plot.OnePad()
if args.pub: main_scan['graph'].SetMarkerSize(0)
main_scan['graph'].SetMarkerColor(1)
main_scan['graph'].Draw('AP')
# main_scan['graph'].Fit('pol4')
# polfunc = main_scan['graph'].GetFunction('pol4')
# print 'Function min at %f' % polfunc.GetMinimumX(0.05, 0.25)

axishist = plot.GetAxisHist(pads[0])
# axishist.SetMinimum(1E-5)
# pads[0].SetLogy(True)
axishist.SetMaximum(args.y_max)
axishist.GetYaxis().SetTitle("- 2 #Delta ln #Lambda(%s)" % fixed_name)
axishist.GetXaxis().SetTitle("%s" % fixed_name)

# main_scan['graph'].Draw('PSAME')
def main(files, label, output, draw_options, title, y_range, ratio_y_range,
         binned_in, x_title, ratio_to, plot_dir, label_pos):
    ROOT.PyConfig.IgnoreCommandLineOptions = True
    ROOT.gROOT.SetBatch(ROOT.kTRUE)
    ROOT.TH1.AddDirectory(0)
    plot.ModTDRStyle()

    # parser = argparse.ArgumentParser()

    # parser.add_argument(
    #     'input', nargs='+', help="""Input files""")
    # parser.add_argument(
    #     '--output', '-o', default='efficiency', help="""Name of the output
    #     plot without file extension""")
    # parser.add_argument('--title', default='Muon ID Efficiency')
    # parser.add_argument('--y-range', default='0,1')
    # parser.add_argument('--ratio-y-range', default='0.5,1.5')
    # parser.add_argument('--binned-in', default='#eta')
    # parser.add_argument('--x-title', default='p_{T} (GeV)')
    # parser.add_argument('--ratio-to', default=None, type=int)
    # parser.add_argument('--plot-dir', '-p', default='./')
    # parser.add_argument('--label-pos', default=1)
    # args = parser.parse_args()

    if plot_dir != '':
        os.system('mkdir -p %s' % plot_dir)

    hists = []

    # file = ROOT.TFile('%s.root' % target)

    # Process each input argument
    for src in files:
        #splitsrc = src.split(':')
        file = ROOT.TFile(src)
        if src.find("gen") >= 0:
            hists.append(file.Get(label + "_tot").Clone())
        else:
            hists.append(file.Get(label).Clone())
        file.Close()

    print hists

    hist = hists[0]

    latex = ROOT.TLatex()
    latex.SetNDC()

    for i in xrange(1, hist.GetNbinsY() + 1):
        bin_label = '%s: [%g,%g]' % (binned_in,
                                     hist.GetYaxis().GetBinLowEdge(i),
                                     hist.GetYaxis().GetBinUpEdge(i))
        canv = ROOT.TCanvas('%s_%i' % (output, i), output)

        if ratio_to is not None:
            pads = plot.TwoPadSplit(0.50, 0.01, 0.01)
        else:
            pads = plot.OnePad()
        slices = []

        if label_pos == 1:
            text = ROOT.TPaveText(0.55, 0.37, 0.9, 0.50, 'NDC')
            legend = ROOT.TLegend(0.18, 0.37, 0.5, 0.50, '', 'NDC')
        elif label_pos == 2:
            text = ROOT.TPaveText(0.55, 0.67, 0.9, 0.80, 'NDC')
            legend = ROOT.TLegend(0.18, 0.67, 0.5, 0.80, '', 'NDC')
        else:
            text = ROOT.TPaveText(0.55, 0.54, 0.9, 0.67, 'NDC')
            legend = ROOT.TLegend(0.55, 0.67, 0.9, 0.80, '', 'NDC')
        text = ROOT.TPaveText(0.55, 0.54, 0.9, 0.67, 'NDC')
        legend = ROOT.TLegend(0.6, 0.54, 0.95, 0.74, '', 'NDC')
        #~ if 'ID' in splitsrc[1]:
        #~ legend = ROOT.TLegend(0.18, 0.67, 0.5, 0.85, '', 'NDC')
        for j, src in enumerate(files):
            #splitsrc = src.split(':')
            htgr = hists[j].ProjectionX(
                '%s_projx_%i' % (hists[j].GetName(), j), i, i)
            #if len(splitsrc) >= 3:
            #    settings = {x.split('=')[0]: eval(x.split('=')[1]) for x in splitsrc[2].split(',')}
            if draw_options[j] != None:
                settings = draw_options[j]
                plot.Set(htgr, **settings)
            htgr.Draw('HIST LP SAME')  #htgr.Draw('SAME')
            legend.AddEntry(htgr)
            slices.append(htgr)
        latex.SetTextSize(0.06)
        #~ text.AddText(args.title)
        #~ text.AddText(bin_label)
        #~ text.SetTextAlign(13)
        #~ text.SetBorderSize(0)
        #~ text.Draw()
        legend.Draw()
        axis = plot.GetAxisHist(pads[0])
        axis.GetYaxis().SetTitle('Efficiency')
        axis.GetXaxis().SetTitle(x_title)
        #~ axis.GetXaxis().SetRange(10,1000)
        axis.SetMinimum(float(y_range[0]))
        axis.SetMaximum(float(y_range[1]))
        pads[0].SetGrid(0, 1)
        pads[0].SetLogx(True)
        pads[0].RedrawAxis('g')

        #~ plot.DrawCMSLogo(pads[0], args.title, bin_label, 0, 0.16, 0.035, 1.2, cmsTextSize=0.5)
        plot.DrawTitle(pads[0], title + ' - ' + bin_label, 1)

        #plot.DrawTitle(pads[0], '18.99 fb^{-1} (13 TeV)', 3)
        plot.DrawTitle(pads[0], '41.29 fb^{-1} (13 TeV)', 3)
        if ratio_to is not None:
            pads[1].cd()
            pads[1].SetLogx(True)
            ratios = []
            for slice in slices:
                ratios.append(slice.Clone())
                ratios[-1].Divide(slices[ratio_to])
            ratios[0].Draw('AXIS')
            plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                         plot.GetAxisHist(pads[1]),
                                         'Ratio to data', True,
                                         float(ratio_y_range[0]),
                                         float(ratio_y_range[1]))
            for j, ratio in enumerate(ratios):
                if j == ratio_to:
                    continue
                ratio.Draw('HIST LP SAME')  #('SAME E0')
            pads[1].SetGrid(0, 1)
            pads[1].RedrawAxis('g')

        outname = '%s.%s.%g_%g' % (output, hist.GetYaxis().GetTitle(),
                                   hist.GetYaxis().GetBinLowEdge(i),
                                   hist.GetYaxis().GetBinUpEdge(i))
        outname = outname.replace('(', '_')
        outname = outname.replace(')', '_')
        outname = outname.replace('.', '_')

        canv.Print('%s/%s.png' % (plot_dir, outname))
        canv.Print('%s/%s.pdf' % (plot_dir, outname))