#include "../GlobalFunctions.hh"


using namespace std;
using namespace RooFit ;


class factor{
private:
public:
    string Channel;
    bool MagUp;
    Int_t year;
    Int_t nEvents;
    Double_t OtherScale;

    factor(){
        Channel = "";
        MagUp = false;
        nEvents = 0;
        OtherScale = 1.0;
    } //empty constructor

    factor(string Channel_tmp, bool MagUp_tmp, Int_t year_tmp, Int_t nEvents_tmp); //default constructor with no other scales
    factor(string Channel_tmp, bool MagUp_tmp, Int_t year, Int_t nEvents_tmp, Double_t OtherScale_tmp); //default constructor
    ~factor();   //destuctor
};

factor::factor(string Channel_tmp, bool MagUp_tmp, Int_t year_tmp, Int_t nEvents_tmp){
    Channel = Channel_tmp;
    MagUp = MagUp_tmp;
    year = year_tmp;
    nEvents = nEvents_tmp;
    OtherScale = 1.0;
    return;
}

factor::factor(string Channel_tmp, bool MagUp_tmp, Int_t year_tmp, Int_t nEvents_tmp, Double_t OtherScale_tmp){
    Channel = Channel_tmp;
    MagUp = MagUp_tmp;
    year = year_tmp;
    nEvents = nEvents_tmp;
    OtherScale = OtherScale_tmp;
    return;
}

factor::~factor(){
    Channel = "";
    MagUp = false;
    year = 0;
    nEvents = 0;
    OtherScale = 1.0;
    return;
}

class oneChannelFactors{ //factors just for one channel, including the lenght, for easier handling
private:
public:
    string Channel = "";
    vector<factor> factorsVec;
    int VecSize = 0;
    oneChannelFactors(){
        Channel = "";
        VecSize = 0;
        factorsVec.clear();
    } //empty constructor
    oneChannelFactors(vector<factor> factorsVec_tmp); //default constructor
    ~oneChannelFactors();   //destuctor
};

oneChannelFactors::~oneChannelFactors(){
    factorsVec.empty();
    Channel = "";
    VecSize = 0;
}

oneChannelFactors::oneChannelFactors(vector<factor> factorsVec_tmp){
    Channel = factorsVec_tmp.at(0).Channel; //todo, check if they are all the same
    factorsVec = factorsVec_tmp;
    VecSize = factorsVec_tmp.size();
    return;
}

class allFactors{
private:
public:
    vector<oneChannelFactors> factorsChannelVec;
    int NoChannels = 0;

    allFactors(){
        NoChannels = 0;
        factorsChannelVec.clear();
    } //empty constructor
    allFactors(int Run, bool RefChan); //default constructor
    ~allFactors();   //destuctor
};

allFactors::allFactors(int Run, bool RefChan){

    oneChannelFactors one_channel_factors_tmp;
    factor factor_tmp;
    vector<factor> factorsVec_tmp;


    if (!RefChan){
        //--------------------------------------------------------------------
        //      KplusPi0
        //--------------------------------------------------------------------
        //Run I
        if (Run == 1){
            factor_tmp = factor("KplusPi0", false, 2011, 507551 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("KplusPi0", true,  2011, 502787 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("KplusPi0", false, 2012, 514015 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("KplusPi0", true,  2012, 500458 );
            factorsVec_tmp.push_back(factor_tmp);
        }

        // Run II
        if (Run == 2){
            factor_tmp = factor("KplusPi0", false, 2015, 500320 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("KplusPi0", true,  2015, 507272 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("KplusPi0", false, 2016, 999419 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("KplusPi0", true,  2016, 1000151 );
            factorsVec_tmp.push_back(factor_tmp);
        }

        one_channel_factors_tmp = oneChannelFactors(factorsVec_tmp);
        factorsChannelVec.push_back(one_channel_factors_tmp);
        factorsVec_tmp.clear();

        //--------------------------------------------------------------------
        //      B0toKstMuMu
        //--------------------------------------------------------------------

        //Run I
        if (Run == 1){
            factor_tmp = factor("B0toKstMuMu", false, 2011, 525851, 1.5  );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("B0toKstMuMu", true,  2011, 506402, 1.5 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("B0toKstMuMu", false, 2012, 257748, 1.5  );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("B0toKstMuMu", true,  2012, 260000, 1.5  );
            factorsVec_tmp.push_back(factor_tmp);
        }

        // Run II
        if (Run == 2){
            factor_tmp = factor("B0toKstMuMu", false, 2015, 502704, 1.5* 13.0/(13.0-4.0) );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("B0toKstMuMu", true,  2015, 503254, 1.5* 12.0/(12.0-1.0) );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("B0toKstMuMu", false, 2016, 657410, 1.5* 5.0/(5.0-4.0) );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("B0toKstMuMu", true,  2016, 707852, 1.5* 5.0/(5.0-1.0) );
            factorsVec_tmp.push_back(factor_tmp);
        }

        one_channel_factors_tmp = oneChannelFactors(factorsVec_tmp);
        factorsChannelVec.push_back(one_channel_factors_tmp);
        factorsVec_tmp.clear();
    }
    else{
        //--------------------------------------------------------------------
        //      RefKplusPi0
        //--------------------------------------------------------------------

        //Run I
        if (Run == 1){
            factor_tmp = factor("RefKplusPi0", false, 2011, 1011831 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("RefKplusPi0", true,  2011, 1007920 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("RefKplusPi0", false, 2012, 1003888 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("RefKplusPi0", true,  2012, 1000278 );
            factorsVec_tmp.push_back(factor_tmp);
        }

        // Run II
        if (Run == 2){
            factor_tmp = factor("RefKplusPi0", false, 2015, -1 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("RefKplusPi0", true,  2015, -1 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("RefKplusPi0", false, 2016, -1 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("RefKplusPi0", true,  2016, -1 );
            factorsVec_tmp.push_back(factor_tmp);
        }

        one_channel_factors_tmp = oneChannelFactors(factorsVec_tmp);
        factorsChannelVec.push_back(one_channel_factors_tmp);
        factorsVec_tmp.clear();


        //--------------------------------------------------------------------
        //      B0toKstJpsi
        //--------------------------------------------------------------------

        //Run I
        if (Run == 1){
            factor_tmp = factor("B0toKstJpsi", false, 2011, 3081998, 1.5 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("B0toKstJpsi", true,  2011, 3076566, 1.5 * 13.0/(13.0-1.0) );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("B0toKstJpsi", false, 2012, 4435958, 1.5 * 15.0/(15.0-1.0) );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("B0toKstJpsi", true,  2012, 4425822, 1.5  );
            factorsVec_tmp.push_back(factor_tmp);
        }

        // Run II
        if (Run == 2){
            factor_tmp = factor("B0toKstJpsi", false, 2015, 874037 , 1.5 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("B0toKstJpsi", true,  2015, 502444 , 1.5 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("B0toKstJpsi", false, 2016, 5033743 , 1.5*125.0/(125.0-2.0) );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("B0toKstJpsi", true,  2016, 4991624 , 1.5*133.0/(133.0-2.0) );
            factorsVec_tmp.push_back(factor_tmp);
        }

        one_channel_factors_tmp = oneChannelFactors(factorsVec_tmp);
        factorsChannelVec.push_back(one_channel_factors_tmp);
        factorsVec_tmp.clear();

        //--------------------------------------------------------------------
        //      BtoXJpsi
        //--------------------------------------------------------------------

        //Run I

        if (Run == 1){
            factor_tmp = factor("BtoXJpsi", false, 2011, -1);//2508491);
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("BtoXJpsi", true,  2011,-1);// 2514495);
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("BtoXJpsi", false, 2012, -1);//2504990);
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("BtoXJpsi", true,  2012,-1);// 2535488);
            factorsVec_tmp.push_back(factor_tmp);
        }

        // Run II
        if (Run == 2){
            factor_tmp = factor("BtoXJpsi", false, 2015, -1);
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("BtoXJpsi", true,  2015, -1 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("BtoXJpsi", false, 2016, 5090001 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("BtoXJpsi", true,  2016, 6055765 );
            factorsVec_tmp.push_back(factor_tmp);
        }

        one_channel_factors_tmp = oneChannelFactors(factorsVec_tmp);
        factorsChannelVec.push_back(one_channel_factors_tmp);
        factorsVec_tmp.clear();


        //--------------------------------------------------------------------
        //      BtoK1MuMu
        //--------------------------------------------------------------------
        /*
    //Run I
    if (Run == 1){
        factor_tmp = factor("BtoK1MuMu", false, 2011, 1038809 );
        factorsVec_tmp.push_back(factor_tmp);
        factor_tmp = factor("BtoK1MuMu", true,  2011, 1027740 );
        factorsVec_tmp.push_back(factor_tmp);
        factor_tmp = factor("BtoK1MuMu", false, 2012, 2003930 );
        factorsVec_tmp.push_back(factor_tmp);
        factor_tmp = factor("BtoK1MuMu", true,  2012, 2008883 );
        factorsVec_tmp.push_back(factor_tmp);
    }

    // Run II
    if (Run == 2){
        factor_tmp = factor("BtoK1MuMu", false, 2015, -1 );
        factorsVec_tmp.push_back(factor_tmp);
        factor_tmp = factor("BtoK1MuMu", true,  2015, -1 );
        factorsVec_tmp.push_back(factor_tmp);
        factor_tmp = factor("BtoK1MuMu", false, 2016, -1 );
        factorsVec_tmp.push_back(factor_tmp);
        factor_tmp = factor("BtoK1MuMu", true,  2016, -1 );
        factorsVec_tmp.push_back(factor_tmp);
    }

    one_channel_factors_tmp = oneChannelFactors(factorsVec_tmp);
    factorsChannelVec.push_back(one_channel_factors_tmp);
    factorsVec_tmp.clear();
    */

        //--------------------------------------------------------------------
        //      BtoK1Jpsi
        //--------------------------------------------------------------------

        //Run I
        if (Run == 1){
            factor_tmp = factor("BtoK1Jpsi", false, 2011, -1 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("BtoK1Jpsi", true,  2011, -1 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("BtoK1Jpsi", false, 2012, 250249, 2.0 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("BtoK1Jpsi", true,  2012, 265250, 2.0 );
            factorsVec_tmp.push_back(factor_tmp);
        }

        // Run II
        if (Run == 2){
            factor_tmp = factor("BtoK1Jpsi", false, 2015, -1 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("BtoK1Jpsi", true,  2015, -1 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("BtoK1Jpsi", false, 2016, -1 );
            factorsVec_tmp.push_back(factor_tmp);
            factor_tmp = factor("BtoK1Jpsi", true,  2016, -1 );
            factorsVec_tmp.push_back(factor_tmp);
        }

        one_channel_factors_tmp = oneChannelFactors(factorsVec_tmp);
        factorsChannelVec.push_back(one_channel_factors_tmp);
        factorsVec_tmp.clear();

    }
    //--------------------------------------------------------------------
    //      PHSP
    //--------------------------------------------------------------------

    /*
    //Run I
    if (Run == 1){
        factor_tmp = factor("PHSP", false, 2011, 94529 );
        factorsVec_tmp.push_back(factor_tmp);
        factor_tmp = factor("PHSP", true,  2011, 91600 );
        factorsVec_tmp.push_back(factor_tmp);
        factor_tmp = factor("PHSP", false, 2012, 175028 );
        factorsVec_tmp.push_back(factor_tmp);
        factor_tmp = factor("PHSP", true,  2012, 203760 );
        factorsVec_tmp.push_back(factor_tmp);
    }

    // Run II
    if (Run == 2){
        factor_tmp = factor("PHSP", false, 2015, 76712 );
        factorsVec_tmp.push_back(factor_tmp);
        factor_tmp = factor("PHSP", true,  2015, 72037 );
        factorsVec_tmp.push_back(factor_tmp);
        factor_tmp = factor("PHSP", false, 2016, 214587 );
        factorsVec_tmp.push_back(factor_tmp);
        factor_tmp = factor("PHSP", true,  2016, 216923 );
        factorsVec_tmp.push_back(factor_tmp);
    }

    one_channel_factors_tmp = oneChannelFactors(factorsVec_tmp);
    factorsChannelVec.push_back(one_channel_factors_tmp);
    factorsVec_tmp.clear();
    */

    NoChannels = factorsChannelVec.size();

}

allFactors::~allFactors(){
    factorsChannelVec.empty();
    NoChannels = 0;
}

//void allFactors::print(){ //TODO
    /*
    cout << "[INFO]\t\tUsing " << NoVariables << " variables." << endl;
    cout << "[INFO]\t\tBranchName \t\t LaTeXName \t\t Unit \t\t DataType" << endl;
    for (vector<MVA_def>::iterator tracksIter1 = AllVariables.begin(); tracksIter1 !=AllVariables.end();++tracksIter1){
        cout<< "[INFO]\t\t" << (*tracksIter1).ReaderName << "\t\t" << (*tracksIter1).LaTeXName << "\t\t" << (*tracksIter1).Unit << "\t\t" << (*tracksIter1).DataType << endl;
    }
    */
//}

oneChannelFactors SignalFactors(int Run =1){

    factor factorSig;
    vector<factor> factorsSigVec;


    //--------------------------------------------------------------------
    //      KplusPi0
    //--------------------------------------------------------------------

    //Run I
    if (Run ==1){
        factorSig = factor("KplusPi0", false, 2011, 507551 );
        factorsSigVec.push_back(factorSig);
        factorSig = factor("KplusPi0", true,  2011, 502787 );
        factorsSigVec.push_back(factorSig);
        factorSig = factor("KplusPi0", false, 2012, 514015 );
        factorsSigVec.push_back(factorSig);
        factorSig = factor("KplusPi0", true,  2012, 500458 );
        factorsSigVec.push_back(factorSig);
    }
    // Run II
    else{
        factorSig = factor("KplusPi0", false, 2015, 500320 );
        factorsSigVec.push_back(factorSig);
        factorSig = factor("KplusPi0", true,  2015, 507272 );
        factorsSigVec.push_back(factorSig);
        factorSig = factor("KplusPi0", false, 2016, 999419 );
        factorsSigVec.push_back(factorSig);
        factorSig = factor("KplusPi0", true,  2016, 1000151 );
        factorsSigVec.push_back(factorSig);
    }
    return oneChannelFactors(factorsSigVec);


}

oneChannelFactors SignalRefFactors(int Run =1){

    factor factorSig;
    vector<factor> factorsSigVec;


    //--------------------------------------------------------------------
    //      RefKplusPi0
    //--------------------------------------------------------------------

    //Run I
    if (Run ==1){
        factorSig = factor("RefKplusPi0", false, 2011, 1011831 );
        factorsSigVec.push_back(factorSig);
        factorSig = factor("RefKplusPi0", true,  2011, 1007920 );
        factorsSigVec.push_back(factorSig);
        factorSig = factor("RefKplusPi0", false, 2012, 1003888 );
        factorsSigVec.push_back(factorSig);
        factorSig = factor("RefKplusPi0", true,  2012, 1000278 );
        factorsSigVec.push_back(factorSig);

    }
    // Run II
    else{
        factorSig = factor("RefKplusPi0", false, 2015, -1 );
        factorsSigVec.push_back(factorSig);
        factorSig = factor("RefKplusPi0", true,  2015, -1 );
        factorsSigVec.push_back(factorSig);
        factorSig = factor("RefKplusPi0", false, 2016, -1 );
        factorsSigVec.push_back(factorSig);
        factorSig = factor("RefKplusPi0", true,  2016, -1 );
        factorsSigVec.push_back(factorSig);
    }
    return oneChannelFactors(factorsSigVec);

}

string HistName(string channel, int year, bool MagUp, bool preselected, bool TM){
    if (preselected) return channel + "_KGammaGammaMuMu_mass_after_preselection_"  + (TM ? "TM_" : "") + to_string(year) + (MagUp ? "MagUp" : "MagDown");
    else             return channel + "_KGammaGammaMuMu_mass_before_preselection_" + (TM ?  "TM_" : "") +  to_string(year) + (MagUp ? "MagUp" : "MagDown");
}

void designCanvas(TCanvas* canvas){
    canvas->SetRightMargin(0.04);
    canvas->SetTopMargin(0.04);
    canvas->SetLeftMargin(0.12);
    canvas->SetBottomMargin(0.12);
    return;

}

void designPlots(TH1F *hist, int color){
    hist->SetLineWidth(2);
    hist->SetLineColor(color);
    hist->GetYaxis()->SetTitleOffset(1.7);
    hist->GetXaxis()->SetTitleOffset(1.0);
    hist->SetTitle("");
}


//the function to loop over all events and merge them into one file; apply cut-based selection while merging
int PlotMasses(int Run =1, bool RefChan=true, bool TruthMatched = false, bool Stripped = false) {

    if (!Kst2Kpluspi0Resolved){
        cout << "Only applicable for KplusPi0 channel! Fix GlobalFunctions.hh" << endl;
        return 0;
    }

    if (Stripped && TruthMatched){
        cout << "[ERROR]\t Stripped data cannot be truthmatched, setting TruthMatched to false" << endl;
        TruthMatched = false;
    }
    TFile *tmpFile = 0;
   // TFile *outputFile = new TFile(Form("%s/data/MC/tmp%s.root",path_to_output_KplusPizero.c_str(), (smallSample ? "_small":"")),"RECREATE");
    TFile *outputFile = new TFile(Form("%s/data/MC/pi0Resolved_background_histos%s.root",path_to_output_KplusPizero.c_str(), (smallSample ? "_small":"")),"RECREATE");

    //std::vector<TH1F*> StrippedMasses;
    //std::vector<TH1F*> PreselectedMasses;

    TH1F *tmp  =  new TH1F("tmp" ,  "tmp",  100, cut_B_plus_M_low, cut_B_plus_M_high);

    //tmp variables
    string decay = "";
    string year_str = "";

        //Data
    allFactors ChannelFactors = allFactors(Run, RefChan); //the boolean is just to differentiate it form the defaul constructor
    factor fac = factor();
    oneChannelFactors SigFac = SignalFactors(Run);
    oneChannelFactors SigRefFac = SignalRefFactors(Run);
    Double_t scaling_factor = 0.0;
    TTree * treeMC, *treeMCold;
    //if (TruthMatched) treeMC = new TTree("DecayTreeTruthMatched");
    //else treeMC = new TTree("DecayTree");

    TCanvas* CanvasPreselectedVec[2][2]; //Create 8 canvases for each year and polarity
    TPaveText  *legend[2][2];
    //This would be so much nicer in python...

    gStyle->SetOptStat(0);


    for (int c = 0; c < 2; c++){
        CanvasPreselectedVec[0][c] = new TCanvas(Form("cPD%i", (Run==1) ? 2011+c : 2015+c), "", 10,10,600,600);
        CanvasPreselectedVec[1][c] = new TCanvas(Form("cPU%i",(Run==1) ? 2011+c : 2015+c), "", 10,10,600,600);
        designCanvas(CanvasPreselectedVec[0][c]);
        designCanvas(CanvasPreselectedVec[1][c]);
        CanvasPreselectedVec[0][c]->SetName(  Form("BkgPresel_%idown", (Run==1) ? 2011+c : 2015+c)  );
        CanvasPreselectedVec[1][c]->SetName(  Form("BkgPresel_%iup", (Run==1) ? 2011+c : 2015+c)  );

        legend[0][c] =new TPaveText ( 0.68 , ( RefChan ? 0.7 : 0.8), 0.93, 0.93, "NDC");
        legend[0][c]->SetFillColor(kWhite);
        legend[1][c] =new TPaveText ( 0.68 , ( RefChan ? 0.7 : 0.8), 0.93, 0.93, "NDC");
        legend[1][c]->SetFillColor(kWhite);

    }

    //I'm pretty sure there is a nicer way to do that, but 9 mod year-2009 gets 1,0,3,2

    oneChannelFactors facIter;
    //for (auto i : ChannelFactors.factorsChannelVec){ //Loop over decay channels
    for (int ch = 0; ch < ChannelFactors.NoChannels; ch++){ //Loop over decay channels: better to have a number for colors and saving the histograms
        facIter = ChannelFactors.factorsChannelVec.at(ch);
        decay = facIter.Channel;
        cout << decay << endl;
        //cout <<  ChannelFactors.NoChannels << endl;

        for (int pos = 0; pos < facIter.VecSize; pos++ ){ //Loop over years and polarities in given decay channel
            //get the mass histograms
            fac = facIter.factorsVec.at(pos);
            year_str = to_string(fac.year);
            if (fac.nEvents == -1) continue;

            if (TruthMatched){
                tmpFile = new TFile(Form("%s/data/MC/%s/%s%s/%s%s_pi0Resolved%s.root",path_to_output_KplusPizero.c_str(),
                                      fac.Channel.c_str(), year_str.c_str(), fac.MagUp ? "up" : "down", year_str.c_str(),fac.MagUp ? "up" : "down",(smallSample ? "_small":"")));
                if (TruthMatched) treeMCold = (TTree *)tmpFile->Get("DecayTreeTruthMatched");
                else treeMCold = (TTree *)tmpFile->Get("DecayTree");
                treeMCold->SetBranchStatus("*",0);
                treeMCold->SetBranchStatus("B_plus_DTF_M",1);
                outputFile->cd();
                treeMC = treeMCold->CloneTree();
                treeMC->Draw(Form("B_plus_DTF_M>>tmp%i",pos), Form("B_plus_DTF_M>%f && B_plus_DTF_M<%f", cut_B_plus_M_low, cut_B_plus_M_high) );
                tmp = (TH1F *)gDirectory->Get(Form("tmp%i",pos));

            }
            else{
                tmpFile = new TFile(Form("%s/data/MC/%s/%s%s/%s%s_pi0Resolved_histos%s.root",path_to_output_KplusPizero.c_str(),
                                         fac.Channel.c_str(), year_str.c_str(), fac.MagUp ? "up" : "down", year_str.c_str(),fac.MagUp ? "up" : "down",(smallSample ? "_small":"")),"READ");
                if (Stripped) tmp = (TH1F *) tmpFile->Get("h_KGammaGammaMuMu_mass_before_preselection")->Clone();
                else tmp = (TH1F *) tmpFile->Get("h_KGammaGammaMuMu_mass_after_preselection")->Clone();
            }

            //Calcualte the needed scale
            if (RefChan) scaling_factor = double((SigRefFac.factorsVec.at(pos)).nEvents)/double(fac.nEvents);
            else         scaling_factor = double((SigFac.factorsVec.at(pos)).nEvents)/double(fac.nEvents);
            scaling_factor = scaling_factor*fac.OtherScale;

            cout << fac.year << (fac.MagUp ? "up  " : "down") << "\t Scaling factor: " << scaling_factor << endl;
            tmp->Scale(scaling_factor);

            cout << "\t\tIntegral: " << tmp->Integral() << endl;
            //Save the scaled histograms
            outputFile->cd();
            tmp ->SetName(HistName(fac.Channel,fac.year,fac.MagUp,0,TruthMatched).c_str());
            tmp ->SetTitle(HistName(fac.Channel,fac.year,fac.MagUp,0,TruthMatched).c_str());
            designPlots(tmp,ch+1);
            tmp->Write(HistName(fac.Channel,fac.year,fac.MagUp,0,TruthMatched).c_str());
            CanvasPreselectedVec[int(fac.MagUp)][fac.year-((Run==1) ? 2011 : 2015)]->cd(); //boolean is dangerous there but f* it
            legend[int(fac.MagUp)][fac.year-((Run==1) ? 2011 : 2015)]->AddText(decay.c_str());
            ((TText*)legend[int(fac.MagUp)][fac.year-((Run==1) ? 2011 : 2015)]->GetListOfLines()->Last())->SetTextColor(ch+1);
            if ( fac.Channel == "KplusPi0" ||  fac.Channel == "RefKplusPi0" ){
                tmp->DrawCopy();
            }
            else{
                tmp->DrawCopy("same");
            }
            CanvasPreselectedVec[int(fac.MagUp)][fac.year-((Run==1) ? 2011 : 2015)]->Modified();
            CanvasPreselectedVec[int(fac.MagUp)][fac.year-((Run==1) ? 2011 : 2015)]->Update();
            //CanvasPreselectedVec[int(fac.MagUp)][fac.year-((Run==1) ? 2011 : 2015)]->Write();

            tmpFile->Close();
        }
    }

    cout << "Drawing legend " << endl;
    //Draw legends

    for (int c = 0; c < 2; c++){
        CanvasPreselectedVec[0][c]->cd();
        legend[0][c]->Draw();
        CanvasPreselectedVec[1][c]->cd();
        legend[1][c]->Draw();
    }


    cout << "Saving histos " << endl;
    for (int c = 0; c < 2; c++){
        CanvasPreselectedVec[0][c]->SaveAs(  Form("%s/data/MC/BackgroundComparisons/BkgSamples_%s_%idown%s%s.pdf",path_to_output_KplusPizero.c_str(),
                                                  (Stripped ? "Stripped" : "Preselected"), (Run==1) ? 2011+c : 2015+c, RefChan ? "_Ref" : "", TruthMatched ? "_TM" : "") ,"jpg");
        CanvasPreselectedVec[1][c]->SaveAs(  Form("%s/data/MC/BackgroundComparisons/BkgSamples_%s_%iup%s%s.pdf",  path_to_output_KplusPizero.c_str(),
                                                 (Stripped ? "Stripped" : "Preselected"), (Run==1) ? 2011+c : 2015+c, RefChan ? "_Ref" : "", TruthMatched ? "_TM" : "") ,"jpg");
     }

    CanvasPreselectedVec[int(fac.MagUp)][fac.year-((Run==1) ? 2011 : 2015)]->Write();

    outputFile->Close();


    return 1;

}

int PlotAllMasses(){
   if (PlotMasses(1,0,0,0) == 0) return 0;
   if (PlotMasses(1,0,0,1) == 0) return 0;
   if (PlotMasses(1,1,0,0) == 0) return 0;
   if (PlotMasses(1,1,0,1) == 0) return 0;
   if (PlotMasses(2,0,0,0) == 0) return 0;
   if (PlotMasses(2,0,0,1) == 0) return 0;
   return 1;
}
