#!/usr/bin/env python
from rpvanalysis import rpvanalysis
import json
import sys

if len(sys.argv) < 2:
    print('Must specify configuration file.')
    sys.exit(1)
print(sys.argv[1])

with open(sys.argv[1]) as f:
    config = json.load(f)

a = rpvanalysis.analyzer()

a.date=config['date']
a.job_name=config['job_name']
a.web_path = config['web_path']
a.hist_path = config['hist_path']
if config['is_mc']:
    a.mc_label = config['mc_label']

a.make_plot_dir()
a.read_bkg_from_csv(config['bkg_file'],is_mc=config['is_mc'])

if 'inject_sig' in config:
    if config['inject_sig']:
        a.read_sig_from_csv(config['sig_file'])
        a.inject_sig(config['sig_dsid'],config['sig_mult'])

if not 'template_type' in config:
    config['template_type'] = 0

if 'MJ_cut' in config:
    a.MJ_cut = config['MJ_cut']

a.template_type = config['template_type']
a.compute_temp_bins()

if 'templates_file' in config:
    a.read_templates(config['templates_file'])
else:
    a.create_templates()

a.verify_templates()
a.compute_dressed_masses(10)

response_list = ['UDR1bU','UDR1bM','UDR1e1','UDR1e2','UDR1e3','UDR1e4']

for region_str in response_list:
  a.plot_response(region_str)

if 'uncertainties' in config:
    if config['uncertainties']:
        a.jet_uncert = config['uncertainties']
else:
    a.compute_uncertainties()
    a.write_uncertainties()
a.drop_2jet_events()

a.compute_dressed_masses(100)

response_list = ['3jCR','3jCRbM','3jCRbU','3jCRl1','3jCRl3']
for region_str in response_list:
    a.plot_response(region_str)

a.drop_3jet_events()
a.compute_dressed_masses(config['n_toys'])

response_list = ['UDR2bU','UDR2bM','UDR2e1','UDR2e2','UDR2e3','UDR2e4','4jbU','4jbM','5jbU','5jbM']
for region_str in response_list:
  a.plot_response(region_str)

if not 'blinded' in config:
    config['blinded'] = False

else:
    if config['blinded']:
        a.MJ_blind = config['MJ_blind']

if 'MJ_plots' in config:
   a.compute_uncert_bins()
   a.compute_shifted_masses()
   a.compute_dressed_MJ_nom()
   a.compute_dressed_MJ_syst()
   print(' creating MJ plots')
   for region_str in config['MJ_plots']:
       print(region_str)
       if 'SR' in region_str:
           a.plot_MJ_shifts(region_str,blinded=config['blinded'])
           a.plot_MJ(region_str,blinded=config['blinded'])
       else:
           a.plot_MJ_shifts(region_str,blinded=False)
           a.plot_MJ(region_str,blinded=False)

a.plot_template_compare()
a.make_webpage()
