Exemplo n.º 1
0
TList* extractObjectFromFile(const char* fileName, const char* name)
{
  TList* objects = new TList();
  TFile file(fileName);
  gROOT->cd();
  TList* keyList = file.GetListOfKeys();
  for (int i = 0; i < keyList->GetSize(); ++i) {
    TKey* key = static_cast<TKey*>(keyList->At(i));
    std::cout<< key->GetName()<< std::endl;
    if (!strcmp(key->GetName(), name)) {
      objects->Add(key->ReadObj()->Clone());
    } else if (!strcmp(key->GetClassName(), "TCanvas")) {
      TCanvas* canvas = static_cast<TCanvas*>(key->ReadObj());
      if (!strcmp(canvas->GetName(), name))
        objects->Add(canvas->Clone());
      TList* objectsFromPad = extractObjectFromPad(canvas, name);
      for (int j = 0; j < objectsFromPad->GetSize(); ++j)
        objects->Add(objectsFromPad->At(j));
    }
  }
  file.Close();
  return objects;
}
Exemplo n.º 2
0
void TnPDrawMass_for_B() {
    gROOT->Macro("rootlogon.C");

    char *infile;
    char *files[maxfile_] = {
        "../../Ana/RD/MuTrk/tnp_pPb_Ana_MuTrk2_2GpP4_1st_Run_for_B_test.root",
    };

    TString outname_in, outname_mid, outname_out;
    TString middle_name, middle_name2;
    int Mode = 0;

    gROOT->SetStyle("Plain");
    gStyle->SetOptStat(0);
    gStyle->SetTitle(0);

    gStyle->SetPaperSize(20,26);
    TCanvas *c1 = new TCanvas();
    Int_t type = 112;
    TString out1 = outfile_ + "[";
    c1->Print(out1);

    for(int l = 0; l < maxfile_; l++) {

        infile = files[l];
        TFile *f = new TFile(infile);
        //TFile finput(infile);
        Mode = l;

        if(Mode == 0) {
            middle_name = "All";
            middle_name2 = "MinBias";
        } else if(Mode == 1) {
            middle_name = "0005";
            middle_name2 = "0 - 5 %";
        } else if(Mode == 2) {
            middle_name = "0510";
            middle_name2 = "5 - 10 %";
        } else if(Mode == 3) {
            middle_name = "1020";
            middle_name2 = "10 - 20 %";
        } else if(Mode == 4) {
            middle_name = "2030";
            middle_name2 = "20 - 30 %";
        } else if(Mode == 5) {
            middle_name = "3040";
            middle_name2 = "30 - 40 %";
        } else if(Mode == 6) {
            middle_name = "4050";
            middle_name2 = "40 - 50 %";
        } else if(Mode == 7) {
            middle_name = "5060";
            middle_name2 = "50 - 60 %";
        } else if(Mode == 8) {
            middle_name = "60100";
            middle_name2 = "60 - 100 %";
        }


        outname_in = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps[";
        outname_mid = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps";
        outname_out = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps]";


        cout<<" Out Name : "<<outname_in<<" "<<outname_mid<<" "<<outname_in<<endl;


        TString tot_dir, dir_pt, dir_eta, dir_suffix, intg;

        TString etabins[etaBins] = {"eta_bin0_", "eta_bin1_", "eta_bin2_", "eta_bin3_", "eta_bin4_"};
        TString ptbins[ptBins] = {"pt_bin0_", "pt_bin1_", "pt_bin2_", "pt_bin3_", "pt_bin4_",
                                  "pt_bin5_", "pt_bin6_"
                                 };
        if(Mode_ == 1) {
            if(TrgBit_ == 1) {
                dir_pt = "MuonTrgNew2CS/PAMu3_pt/";
                dir_eta = "MuonTrgNew2CS/PAMu3_eta/";
                dir_suffix = "_cbPlusExpo";
                intg = "MuonTrgNew2CS/PAMu3_1bin_pt_eta/eta_bin0__pt_bin0_";
            } else if(TrgBit_ == 2) {
                dir_pt = "MuonTrgNew/HLTL1HighQ_pt/";
                dir_eta = "MuonTrgNew/HLTL1HighQ_eta/";
                dir_suffix = "_cbPlusExpo";
                intg = "MuonTrgNew/HLTL1HighQ_1bin_pt_eta/pt_bin0__eta_bin0_";
            } else if(TrgBit_ == 3) {
                dir_pt = "MuonTrgNew/HLTL2_pt/";
                dir_eta = "MuonTrgNew/HLTL2_eta/";
                dir_suffix = "_cbPlusExpo";
                intg = "MuonTrgNew/HLTL2_1bin_pt_eta/pt_bin0__eta_bin0_";
            }
        } else if (Mode_ == 2) {
            dir_pt = "MuonTrk2/isTrk_pt/";
            dir_eta = "MuonTrk2/isTrk_eta/";
            dir_suffix = "_twoGaussPlusPoly4";
            intg = "MuonTrk2/isTrk_1bin_pt_eta/eta_bin0__pt_bin0_";
        } else if (Mode_ == 3) {
            dir_pt = "/MuonIDNew2CS/PassingTrk_pt/";
            dir_eta = "/MuonIDNew2CS/PassingTrk_eta/";
            dir_suffix = "_cbPlusPoly";
            intg = "/MuonIDNew2CS/PassingTrk_1bin_eta_pt/eta_bin0__pt_bin0_";
        }
        ///*

        cout<<" Total directory : "<<tot_dir<<endl;
        gStyle->SetPaperSize(20,26);

        Int_t type = 112;

        c1->Print(outname_in);
        int cnt = 0;

        TCanvas *tmp1 = new TCanvas();
        tmp1->cd();

        TString title;
        title = "J/#psi " + Cat3 + " Efficiency Heavy Ion TnP Result (" + middle_name2 + ")";

        TLatex fitInfo;
        fitInfo.SetTextAlign(13);
        fitInfo.SetTextSize(0.05);
        fitInfo.DrawLatex(0.05,0.95, title);
        fitInfo.DrawLatex(0.05,0.90, data_set);
        fitInfo.SetTextSize(0.04);
        fitInfo.DrawLatex(0.05,0.80, "FitFunction Condition");
        fitInfo.SetTextSize(0.03);
        if(Mode_ == 1) {
            fitInfo.DrawLatex(0.1,0.60,"CBShape::signal(mass, mean[3.1,3.0,3.2], sigma[0.05,0.01,0.1], alpha[1.0, 0.2, 2.0], n[2, 0.5, 100.])");
            fitInfo.DrawLatex(0.1,0.55,"Exponential::backgroundPass(mass, lp[0,-5,5])");
            fitInfo.DrawLatex(0.1,0.50,"Exponential::backgroundFail(mass, lf[0,-5,5])");
        } else if(Mode_ == 2) {
            fitInfo.DrawLatex(0.1,0.70,"Gaussian::G1(mass, mean, sigma1[0.15,0.05,0.25])");
            fitInfo.DrawLatex(0.1,0.65,"Gaussian::G2(mass, mean, sigma2[0.02,0.01,0.1])");
            fitInfo.DrawLatex(0.1,0.60,"SUM::signal(coef[0.1,0,1]*G1,G2)");
            fitInfo.DrawLatex(0.1,0.55,"Chebychev::backgroundPass(mass, {cPass[0,-0.5,0.5], cPass2[0,-0.5,0.5]})");
            fitInfo.DrawLatex(0.1,0.50,"Chebychev::backgroundFail(mass, {cFail[0,-0.5,0.5], cFail2[0,-0.5,0.5]})");
        } else {
            fitInfo.DrawLatex(0.1,0.60,"CBShape::signal(mass, mean[3.1,3.0,3.2], sigma[0.05,0.01,0.1], alpha[1.0, 0.2, 3.0], n[1, 1.0, 100.])");
            fitInfo.DrawLatex(0.1,0.55,"Chebychev::backgroundPass(mass, {cPass[0,-0.5,0.5], cPass2[0,-0.5,0.5]})");
            fitInfo.DrawLatex(0.1,0.50,"Chebychev::backgroundFail(mass, {cFail[0,-0.5,0.5], cFail2[0,-0.5,0.5]})");
        }
        fitInfo.SetTextSize(0.04);
        fitInfo.DrawLatex(0.05,0.40,"Bin Information");
        fitInfo.SetTextSize(0.03);
        fitInfo.DrawLatex(0.1,0.30,"#eta : -2.4,-1.97,-1.72,-1.47,-1.22,-0.97,-0.72,0.47,0.22,0.03,0.28,0.53,0.78,1.03,1.46");
        fitInfo.DrawLatex(0.1,0.25,"p_{T} [GeV/c] : 6.5,7.5,8.5,9.5,11,14,30");
        c1 = (TCanvas *)tmp1->Clone();
        c1->Print(outname_mid);
        c1->Print(outfile_);

        TString mid_title = "Centrality : (" + middle_name2 + ")";
        TString leg_title = Cat2 + " " + Cat3 + " Efficiency (" + middle_name2 + ")";

        if(Mode < 1) {
            // pt
            for(int j = 0; j < ptBins; j++) {
                cout<<" dir_pt : "<<dir_pt<<", ptbins : "<<ptbins[j]<<", dir_suffix : "<<dir_suffix<<endl;
                TString tot_dir = dir_pt + ptbins[j] + dir_suffix;
                f->cd(tot_dir);
                cout<<" tot_dir : "<<tot_dir<<endl;
                TDirectory *root_dir = gDirectory;
                TIter rootnextkey( root_dir->GetListOfKeys() );
                root_dir->cd();
                TKey *rootkey;
                TCanvas *ctmp = new TCanvas();
                ctmp->cd();


                TLatex l;
                l.SetTextAlign(13);
                l.SetTextSize(0.06);
                l.DrawLatex(0.1,0.8,mid_title);
                l.DrawLatex(0.1,0.6,"Bin : ");
                l.SetTextSize(0.04);
                l.DrawLatex(0.1,0.5,tot_dir);
                ctmp->Update();
                c1 = (TCanvas *)ctmp->Clone();
                c1->Print(outname_mid);
                c1->Print(outfile_);

                while( rootkey = (TKey*)rootnextkey() )
                {
                    TObject *rootobj = rootkey->ReadObj();
                    TDirectory *rdir = gDirectory;
                    TIter rdirnextkey(rdir->GetListOfKeys());
                    rdir->cd();
                    TKey *dir_key;
                    while( dir_key = (TKey*)rdirnextkey())
                    {
                        if (rootobj->IsA()->InheritsFrom("TCanvas")) {
                            c1 = (TCanvas *)rootobj;
                            c1->Print(outname_mid);
                            c1->Print(outfile_);
                            cnt++;
                            cout<<"Count : "<<cnt<<endl;
                            if(cnt > 0) break;
                        }
                    }
                }
            }

            // eta
            for(int j = 0; j < etaBins; j++) {
                TString tot_dir = dir_eta + etabins[j] + dir_suffix;
                cout<<" tot_dir : "<<tot_dir<<endl;
                f->cd(tot_dir);
                TDirectory *root_dir = gDirectory;
                TIter rootnextkey( root_dir->GetListOfKeys() );
                root_dir->cd();
                TKey *rootkey;

                TCanvas *ctmp = new TCanvas();
                ctmp->cd();

                TLatex l;
                l.SetTextAlign(13);
                l.SetTextSize(0.06);
                l.DrawLatex(0.1,0.8,mid_title);
                l.DrawLatex(0.1,0.6,"Bin : ");
                l.SetTextSize(0.04);
                l.DrawLatex(0.1,0.5,tot_dir);
                ctmp->Update();
                c1 = (TCanvas *)ctmp->Clone();
                c1->Print(outname_mid);
                c1->Print(outfile_);

                while( rootkey = (TKey*)rootnextkey() )
                {
                    TObject *rootobj = rootkey->ReadObj();
                    TDirectory *rdir = gDirectory;
                    TIter rdirnextkey(rdir->GetListOfKeys());
                    rdir->cd();
                    TKey *dir_key;
                    while( dir_key = (TKey*)rdirnextkey())
                    {
                        if (rootobj->IsA()->InheritsFrom("TCanvas")) {
                            c1 = (TCanvas *)rootobj;
                            c1->Print(outname_mid);
                            c1->Print(outfile_);
                            cnt++;
                            cout<<"Count : "<<cnt<<endl;
                            if(cnt > 0) break;
                        }
                    }
                }
            }
        }

        tot_dir = intg + dir_suffix;
        f->cd(tot_dir);
        cout<<" tot_dir : "<<tot_dir<<endl;
        TDirectory *root_dir = gDirectory;
        TIter rootnextkey( root_dir->GetListOfKeys() );
        root_dir->cd();
        TKey *rootkey;
        TCanvas *ctmp = new TCanvas();
        ctmp->cd();


        TLatex l;
        l.SetTextAlign(13);
        l.SetTextSize(0.06);
        l.DrawLatex(0.1,0.8,mid_title);
        l.DrawLatex(0.1,0.6,"Bin : ");
        l.SetTextSize(0.04);
        l.DrawLatex(0.1,0.5,tot_dir);
        ctmp->Update();
        c1 = (TCanvas *)ctmp->Clone();
        c1->Print(outname_mid);
        c1->Print(outfile_);

        while( rootkey = (TKey*)rootnextkey() )
        {
            TObject *rootobj = rootkey->ReadObj();
            TDirectory *rdir = gDirectory;
            TIter rdirnextkey(rdir->GetListOfKeys());
            rdir->cd();
            TKey *dir_key;
            while( dir_key = (TKey*)rdirnextkey())
            {
                if (rootobj->IsA()->InheritsFrom("TCanvas")) {
                    c1 = (TCanvas *)rootobj;
                    c1->Print(outname_mid);
                    c1->Print(outfile_);
                    cnt++;
                    cout<<"Count : "<<cnt<<endl;
                    if(cnt > 0) break;
                }
            }
        }
    }
    c1->Print(outname_out);
    TString out2 = outfile_ + "]";
    c1->Print(out2);


}
void TnPDrawMass_test_5eta5()
{
    char *infile;
    //char *files = "/afs/cern.ch/work/g/goni/cms760pre4/src/test_TNP/TnP/mc/out/gputEveryCut_mc_allDirection_v24_nominalCond_5etaBins_cutG_all_2G_v1.root";
    //char *files = "/afs/cern.ch/work/g/goni/cms760pre4/src/test_TNP/TnP/mc/out/gputEveryCut_mc_allDirection_v24_nominalCond_5etaBins_cutG_all_Multi_v1.root";
    //char *files = "/afs/cern.ch/work/g/goni/cms760pre4/src/test_TNP/TnP/mc/out/gputEveryCut_mc_allDirection_v24_nominalCond_5etaBins_cutG_all_PAMu7_v1.root";
    //char *files = "/afs/cern.ch/work/g/goni/cms760pre4/src/test_TNP/TnP/mc/out/gputEveryCut_mc_allDirection_v24_nominalCond_5etaBins_cutG_all_merge_v1.root";
    //char *files = "/afs/cern.ch/work/g/goni/cms760pre4/src/test_TNP/TnP/mc/out/gputEveryCut_mc_allDirection_v24_nominalCond_5etaBins_cutG_all_narrow_v1.root";
    char *files = "/afs/cern.ch/work/g/goni/cms760pre4/src/test_TNP/TnP/data/outputEveryCut_data_allDirection_v24_nominalCond_5etaBins_cutG_all_nominal_v8_oldeta.root";

    TString outname_in, outname_mid, outname_out;
    TString middle_name, middle_name2;

    gROOT->SetStyle("Plain");
    gStyle->SetOptStat(0);
    gStyle->SetTitle(0);

    gStyle->SetPaperSize(20,26);
    TCanvas *c1 = new TCanvas();
    Int_t type = 112;
    TString out1 = outfile_ + "[";
		c1->SetLogy();
    c1->Print(out1);

    infile = files;
    TFile *f = new TFile(infile);

    outname_in = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps[";
    outname_mid = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps";
    outname_out = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps]";


    cout<<" Out Name : "<<outname_in<<" "<<outname_mid<<" "<<outname_in<<endl;
        

    TString tot_dir; //dir_suffix;
    
    //TString ptbins[ptBins] = {"pt_bin0_", "pt_bin1_", "pt_bin2_", "pt_bin3_", "pt_bin4_",
		//								"pt_bin5_", "pt_bin6_", "pt_bin7_", "pt_bin8_",};//1
    //TString ptbins1[ptBins1] = {"3.3 - 3.8 GeV", "3.8 - 4.3  GeV", "4.3 - 5 GeV", "5 - 6 GeV", "6 - 7 GeV",
		//								"7 - 8 GeV", "8 - 10 GeV", "10 - 13 GeV", "13 - 30 GeV"};//1
    TString dir_pt[ptBins] = {"tpTree/ptBin_eta5_0/", "tpTree/ptBin_eta5_1/", "tpTree/ptBin_eta5_2/", "tpTree/ptBin_eta5_3/", "tpTree/ptBin_eta5_4/", "tpTree/ptBin_eta5_5/", "tpTree/ptBin_eta5_6/", "tpTree/ptBin_eta5_7/"};//5
    TString ptbins1[ptBins1] = {"1.3 - 1.6 GeV", "1.6 - 1.8 GeV", "1.8 - 2.0  GeV", "2.0 - 2.6 GeV", "2.6 - 3.4 GeV", "3.4 - 4.8 GeV", "4.8 -6.0 GeV", "6.0 - 30 GeV"};//5
   

    //TString ptbins[ptBins] = {"pt_bin0_", "pt_bin1_", "pt_bin2_", "pt_bin3_", "pt_bin4_",
	  //								"pt_bin5_", "pt_bin6_", "pt_bin7_", "pt_bin8_", "pt_bin9_"};//3
    //TString ptbins1[ptBins1] = {"0 - 3.3 GeV", "3.3 - 3.8  GeV", "3.8 - 4.3 GeV", "4.3 - 5 GeV", "5 -6 GeV",
		//								"6 - 7 GeV", "7 - 8 GeV", "8 - 10 GeV", "10 - 13 GeV", "13 - 30 GeV"};//3
    
    //TString ptbins[ptBins] = {"pt_bin0_", "pt_bin1_", "pt_bin2_", "pt_bin3_", "pt_bin4_",
	  //								"pt_bin5_", "pt_bin6_", "pt_bin7_", "pt_bin8_", "pt_bin9_"};//4
    //TString ptbins1[ptBins1] = {"0 - 3.3 GeV", "3.3 - 3.8  GeV", "3.8 - 4.3 GeV", "4.3 - 5 GeV", "5 -6 GeV",
		//								"6 - 7 GeV", "7 - 8 GeV", "8 - 10 GeV", "10 - 13 GeV", "13 - 30 GeV"};//4
     
    //TString ptbins[ptBins] = {"pt_bin0_", "pt_bin1_", "pt_bin2_", "pt_bin3_", "pt_bin4_",
	  //								"pt_bin5_", "pt_bin6_", "pt_bin7_", "pt_bin8_", "pt_bin9_"};//5
    //TString ptbins1[ptBins1] = {"0 - 3.3 GeV", "3.3 - 3.8  GeV", "3.8 - 4.3 GeV", "4.3 - 5 GeV", "5 -6 GeV",
		//								"6 - 7 GeV", "7 - 8 GeV", "8 - 10 GeV", "10 - 13 GeV", "13 - 30 GeV"};//5

    //dir_pt = "tpTree/ptBin_eta1/";
    //dir_pt = "tpTree/ptBin_eta3/";
    //dir_pt = "tpTree/ptBin_eta3/";
    //dir_pt = "tpTree/ptBin_eta5/";
    //dir_pt = "tpTree/ptBin_eta5/";

    //dir_suffix = "_cbGaussPlusPoly1";
    //dir_suffix = "_cbGaussPlusPoly4";
    TString dir_suffix[ptBins]= {"_cbGaussPlusExpo5_0","_cbGaussPlusExpo5_1","_cbGaussPlusExpo5_2","_cbGaussPlusExpo5_3","_cbGaussPlusExpo5_4","_cbGaussPlusExpo5_5", "_cbGaussPlusExpo5_6", "_cbGaussPlusExpo5_7"};   
    //dir_suffix = "_GaussPlusExpo";
    //dir_suffix = "_twoGaussPlusExpo";
    gStyle->SetPaperSize(20,26);

    c1->Print(outname_in);
    int cnt = 0;

    TCanvas *tmp1 = new TCanvas();
    tmp1->cd();

    TString title;
    title = "J/#psi Efficiency Heavy Ion TnP Result (" + middle_name2 + ")";

    c1 = (TCanvas *)tmp1->Clone();
    c1->Print(outname_mid);
    c1->Print(outfile_);

    TString mid_title = "Centrality : (" + middle_name2 + ")";
    TString leg_title = Cat2 + " Efficiency (" + middle_name2 + ")";

    // pt
    for(int j = 0; j < ptBins; j++){
        //TString tot_dir = dir_pt + "abseta_bin0__event_PrimaryVertex_z_bin0__" + ptbins[j] + "_tag_eta_bin0__tag_pt_bin0__Acc_JPsi_pass__Calo_pass__tag_PAMu3_standard_pass_" + dir_suffix;
        TString tot_dir = dir_pt[j] + "abseta_bin0__event_PrimaryVertex_z_bin0__pt_bin0__tag_eta_bin0__tag_pt_bin0__Acc_JPsiG_pass__Calo_pass__tag_PAMu3_standard_pass_" + dir_suffix[j];//2G,PAMu3,merge
        //TString tot_dir = dir_pt + "abseta_bin0__event_PrimaryVertex_z_bin0__" + ptbins[j] + "_tag_eta_bin0__tag_pt_bin0__Acc_JPsiG_pass__Calo_pass__tag_PAMu7_standard_pass_" + dir_suffix;//PAMu7
        //TString tot_dir = dir_pt + "abseta_bin0__event_PrimaryVertex_z_bin0__pair_probeMultiplicity_bin0__" + ptbins[j] + "_tag_eta_bin0__tag_pt_bin0__Acc_JPsiG_pass__Calo_pass__tag_PAMu3_standard_pass_" + dir_suffix;//multi
        //TString tot_dir = dir_pt + "abseta_bin0__event_PrimaryVertex_z_bin0__" + ptbins[j] + "_tag_eta_bin0__tag_pt_bin0__Acc_JPsi_pass__Calo_pass__tag_PAMu3_standard_pass_" + dir_suffix;//merge
        //
      
  
        f->cd(tot_dir);
        cout<<" tot_dir : "<<tot_dir<<endl;
        TDirectory *root_dir = gDirectory;
        TIter rootnextkey( root_dir->GetListOfKeys() );
        root_dir->cd();
        TKey *rootkey;
        TCanvas *ctmp = new TCanvas();
        ctmp->cd();

        TLatex l;
        l.SetTextAlign(13);
        l.SetTextSize(0.06);
        l.DrawLatex(0.1,0.8,mid_title);
        l.DrawLatex(0.1,0.6,"Bin : ");
        l.SetTextSize(0.04);
        //l.DrawLatex(0.1,0.5,tot_dir);
        l.DrawLatex(0.1,0.5,ptbins1[j]);
        

        ctmp->Update();
        c1 = (TCanvas *)ctmp->Clone();
        c1->Print(outname_mid);
        c1->Print(outfile_);

        while( rootkey = (TKey*)rootnextkey() )
        {
            TObject *rootobj = rootkey->ReadObj();
            TDirectory *rdir = gDirectory;
            TIter rdirnextkey(rdir->GetListOfKeys());
            rdir->cd();
            TKey *dir_key;
            while( dir_key = (TKey*)rdirnextkey())
            {
                if (rootobj->IsA()->InheritsFrom("TCanvas")){
                    c1 = (TCanvas *)rootobj;
		c1->SetLogy();
		c1->Modified();
		c1->Update();
                    c1->Print(outname_mid);
                    c1->Print(outfile_);
                    cnt++;
                    cout<<"Count : "<<cnt<<endl;
                    if(cnt > 0) break;
                }
            }
        }
    }
    c1->Print(outname_out);
    TString out2 = outfile_ + "]";
    c1->Print(out2);
}
Exemplo n.º 4
0
TCanvas* getRatio(TString plotName, int verbose, TString outputFile){
  // ============================
  //  Set Root Style
  // ============================
  TStyle myStyle("HHStyle","HHStyle");
  setHHStyle(myStyle);
  TGaxis::SetMaxDigits(2);
  myStyle.cd();
  gROOT->SetStyle("HHStyle");
  
  // draw data uncertainties as bands
  bool bands=true;

  // compare current with old result
  bool compare=false;
  TString oldResult="/afs/naf.desy.de/group/cms/scratch/tophh/tmp/OldCombination/";

  // open file
  TFile* file = TFile::Open(outputFile, "READ");
  // dont associate new objects with file to be able to close it in the end
  gROOT->cd();
  // get canvas for chosen cross section
  TCanvas* canvas = (TCanvas*)(file->Get("finalXSec/"+plotName+"Norm")->Clone());
  // GET DATA: with final errors from canvas
  TGraphAsymmErrors* dataRaw  = (TGraphAsymmErrors*)canvas->GetPrimitive("dataTotalError");
  TGraphAsymmErrors* dataStat = (TGraphAsymmErrors*)canvas->GetPrimitive("dataStatError");
  // GET DATA: create rebinned histo
  std::map< TString, std::vector<double> > binning_ = makeVariableBinning();
  int Nbins = std::abs(binning_[plotName][binning_[plotName].size()-1]-binning_[plotName][0])*100;
  if(plotName.Contains("topY")) Nbins/=10;
  if(verbose>1) std::cout << Nbins << std::endl;
  TH1F* datatemp= new TH1F("data"+plotName, "data"+plotName, Nbins, binning_[plotName][0], binning_[plotName][binning_[plotName].size()-1]);
  reBinTH1F(*datatemp, binning_[plotName], 0);
  // GET DATA: refill TGraphAsymmErrors to rebinned histo
  for(int bin=1; bin<=datatemp->GetNbinsX(); ++bin){
    if(verbose>1){
      std::cout << "bin: " << bin << std::endl;
      std::cout << dataRaw->GetY()[bin];
    }
    datatemp->SetBinContent(bin, dataRaw->GetY()[bin]);
    double err=dataRaw->GetErrorYhigh(bin);
    if(err<dataRaw->GetErrorYlow(bin)) err=dataRaw->GetErrorYlow(bin);
    if(verbose>1) std::cout << " +- " << err << std::endl;
    datatemp->SetBinError(bin, err);
  }
  // GET DATA: delete empty bins
  TH1F* data=killEmptyBins((TH1F*)datatemp->Clone(), verbose);
  data->GetXaxis()->SetTitle(xSecLabelName(plotName));
  if(verbose>1){
    for(int bin=1; bin<=data->GetNbinsX(); ++bin){
      std::cout << "bin: " << bin << std::endl;
      std::cout << data->GetBinContent(bin) << " +- " << data->GetBinError(bin) << std::endl;
    }
  }

  // GET THEORY: binned curves from canvas
  TH1F* plotNNLO     = (TH1F*)canvas->GetPrimitive(plotName+"nnlo"   );
  TH1F* plotMadGraph = (TH1F*)canvas->GetPrimitive(plotName          );
  TH1F* plotmcatnlo  = (TH1F*)canvas->GetPrimitive(plotName+"MC@NLO2");
  if(!plotmcatnlo) plotmcatnlo  = (TH1F*)canvas->GetPrimitive(plotName+"MC@NLO");
  TGraphAsymmErrors* plotmcatnloerror = (TGraphAsymmErrors*)canvas->GetPrimitive(plotName+"MC@NLOerrorBand");
  TH1F* plotpowheg   = (TH1F*)canvas->GetPrimitive(plotName+"POWHEG");
  TH1F* plotpowhegherwig = (TH1F*)canvas->GetPrimitive(plotName+"POWHEGHERWIG");
  std::vector<TH1F*>hist_;
  // GET THEORY: delete empty bins
  // a) peturbative QCD
  TH1F* finalNNLO=0;
  if(plotNNLO        ){
    // delete empty bins
    TH1F* tempNNLO=killEmptyBins(plotNNLO, verbose);
    std::cout << tempNNLO->GetName() << std::endl;  
    // delete bins put of range
    int Nnnlobins = std::abs(binning_[plotName][binning_[plotName].size()-1]-binning_[plotName][0])*10;
    finalNNLO=new TH1F(tempNNLO->GetName(),tempNNLO->GetTitle(), Nnnlobins, binning_[plotName][0], binning_[plotName][binning_[plotName].size()-1]);
    reBinTH1F(*finalNNLO, binning_[plotName], 0);
    for(int bin=0; bin<=tempNNLO->GetNbinsX()+1; ++bin){
      double binlowedge=tempNNLO->GetBinLowEdge(bin); 
      if(plotName.Contains("topPt")&&binlowedge==1.) binlowedge=0.;
      //std::cout << "binlowedge: " << binlowedge << std::endl;      
      for(int binf=0; binf<=finalNNLO->GetNbinsX()+1; ++binf){
	//std::cout << "scanlowedge: " << finalNNLO->GetBinLowEdge(binf) << std::endl;
	if(binlowedge==finalNNLO->GetBinLowEdge(binf)){
	  //std::cout << "fits!" << std::endl;
	  finalNNLO->SetBinContent(binf, tempNNLO->GetBinContent(bin)) ;
	  finalNNLO->SetBinError(binf, tempNNLO->GetBinError(bin)); 
	}
      }
    }
  }
  // b) MC@NLO errorbands
  if(plotmcatnloerror&&plotmcatnlo){
    TH1F*   plotmcatnloerror1 =(TH1F*)((killEmptyBins(plotmcatnlo, verbose))->Clone((TString)plotmcatnloerror->GetName()+"Up"));
    TH1F*   plotmcatnloerror2 =(TH1F*)((killEmptyBins(plotmcatnlo, verbose))->Clone((TString)plotmcatnloerror->GetName()+"Dn"));
    for(int p=0; p<plotmcatnloerror->GetN(); ++p){
      plotmcatnloerror1->SetBinContent(p, plotmcatnloerror->GetErrorYhigh(p)+plotmcatnloerror->GetY()[p]);
      plotmcatnloerror2->SetBinContent(p, plotmcatnloerror->GetY()[p]-plotmcatnloerror->GetErrorYlow(p));
    }
    plotmcatnloerror1->SetLineStyle(1);
    plotmcatnloerror2->SetLineStyle(1);
    hist_.push_back( killEmptyBins(plotmcatnloerror1, verbose) );
    hist_.push_back( killEmptyBins(plotmcatnloerror2, verbose) );
  }
  // a1) Ahrens
  if(finalNNLO&&(plotName.Contains("ttbarMass")||plotName.Contains("ttbarPt"))) hist_.push_back(finalNNLO);
  // c) MC theories
  if(plotMadGraph    ) hist_.push_back( killEmptyBins(plotMadGraph    , verbose) );
  if(plotmcatnlo     ) hist_.push_back( killEmptyBins(plotmcatnlo     , verbose) );
  if(plotpowheg      ) hist_.push_back( killEmptyBins(plotpowheg      , verbose) );
  if(plotpowhegherwig) hist_.push_back( killEmptyBins(plotpowhegherwig, verbose) );
  // a2) Kidonakis
  if(finalNNLO&&(plotName.Contains("topY")||plotName.Contains("topPt"))) hist_.push_back(finalNNLO);
  if(compare){
    // reference results from a different analysis setup
    // GET DATA2: with final errors from canvas
    TString modfile=oldResult;
    modfile+=outputFile;
    TFile* file2 = TFile::Open(modfile, "READ");
    TCanvas* canvas2 = (TCanvas*)(file2->Get("finalXSec/"+plotName+"Norm")->Clone());
    TGraphAsymmErrors* data2Raw     = (TGraphAsymmErrors*)canvas2->GetPrimitive("dataTotalError");
    TH1F* data2temp= new TH1F("data"+plotName, "data"+plotName, Nbins, binning_[plotName][0], binning_[plotName][binning_[plotName].size()-1]);
    reBinTH1F(*data2temp, binning_[plotName], 0);
    // GET DATA2: refill TGraphAsymmErrors to rebinned histo
    for(int bin=1; bin<=data2temp->GetNbinsX(); ++bin){
      data2temp->SetBinContent(bin, data2Raw->GetY()[bin]);
      double err=data2Raw->GetErrorYhigh(bin);
      if(err<data2Raw->GetErrorYlow(bin)) err=data2Raw->GetErrorYlow(bin);
      data2temp->SetBinError(bin, err);
    }
    // GET DATA: delete empty bins
    TH1F* data2=killEmptyBins((TH1F*)data2temp->Clone(), verbose);
    data2->GetXaxis()->SetTitle(xSecLabelName(plotName));
    for(int bin=1; bin<=data2->GetNbinsX(); ++bin){
      std::cout << plotName << "bin: " << bin << std::endl;
      std::cout << "old: " << data2->GetBinContent(bin) << " +- " << data2->GetBinError(bin) << std::endl;
      if(data->GetNbinsX()==data2->GetNbinsX()) std::cout << "new: " << data->GetBinContent(bin)  << " +- " << data->GetBinError(bin)  << std::endl;
      if(bin==data2->GetNbinsX()) std::cout << std::endl;
    }
    data2->SetFillStyle(0);
    data2->SetMarkerColor(kBlack);
    data2->SetLineColor(kBlack);
    data2->SetLineWidth(3);
    hist_.push_back(data2);
  }

  // set axis colors to white because otherwise it spoils the ratio plot on top of it
  plotMadGraph->GetXaxis()->SetLabelColor(0);
  plotMadGraph->GetXaxis()->SetTitleColor(0);
  
  // create ratio canvas
  std::vector<TCanvas*> plotCanvas_;
  double max= 1.5;
  double min= 0.5;
  if(plotName.Contains("lepPt"    )){min=bands ? 0.85 : 0.85;max=bands ? 1.29 : 1.29;}
  if(plotName.Contains("lepEta"   )){min=bands ? 0.85 : 0.75;max=bands ? 1.35 : 1.25;}
  if(plotName.Contains("bqPt"     )){min=bands ? 0.7  : 0.7 ;max=bands ? 1.5  : 1.5 ;}
  if(plotName.Contains("bqEta"    )){min=bands ? 0.85 : 0.85;max=bands ? 1.25 : 1.15;}
  if(plotName.Contains("bbbarMass")){min=bands ? 0.3  : 0.3 ;max=bands ? 1.85 : 1.75;}
  if(plotName.Contains("bbbarPt"  )){min=bands ? 0.61 : 0.61;max=bands ? 1.49 : 1.39;}
  if(plotName.Contains("Njets"    )){min=bands ? 0.15 : 0.15;max=bands ? 1.95 : 1.95;}
  if(plotName.Contains("rhos"     )){min=bands ? 0.1  : 0.1 ;max=bands ? 2.59 : 1.9; }
  if(plotName.Contains("lbMass"   )){min=bands ? 0.7  : 0.7 ;max=bands ? 1.45 : 1.35;}
  if(plotName.Contains("topPt"    )){
    if(     plotName.Contains("Sub" )){min=bands ? 0.7  : 0.7 ;max=bands ? 1.59 : 1.59;}
    else if(plotName.Contains("Lead")){min=bands ? 0.7  : 0.7 ;max=bands ? 1.59 : 1.59;}
    else                              {min=bands ? 0.75 : 0.75;max=bands ? 1.59 : 1.59;}
  }
  if(plotName.Contains("topY"       )){min=bands ? 0.85 : 0.85;max=bands ? 1.19 : 1.15;}
  if(plotName.Contains("ttbarPt"    )){min=bands ? 0.5  : 0.5 ;max=bands ? 1.79 : 1.39;}
  if(plotName.Contains("ttbarY"     )){min=bands ? 0.8  : 0.8 ;max=bands ? 1.39 : 1.29;}
  if(plotName.Contains("ttbarMass"  )){min=bands ? 0.7  : 0.7 ;max=bands ? 1.5  : 1.5 ;}
  if(plotName.Contains("topPtTtbar" )){min=bands ? 0.6  : 0.6 ;max=bands ? 1.79 : 1.79;}
  if(plotName.Contains("ttbarDelPhi")){min=bands ? 0.85 : 0.85;max=bands ? 1.25 : 1.15;}
  if(plotName.Contains("PhiStar"    )){min=bands ? 0.85 : 0.85;max=bands ? 1.25 : 1.15;}
  plotCanvas_.push_back(drawFinalResultRatio(data, min, max, myStyle, 0, hist_, (TCanvas*)(canvas->Clone()), -1, -1, dataStat, false, true, bands));
  plotCanvas_[0]->Draw();
  plotCanvas_[0]->Update();
  // close file
  file->Close();
  // return
  return plotCanvas_[0];
}
void EstimateBg_76X(bool save=0, std::string in = "",
		std::string out = "/afs/cern.ch/user/j/jkarancs/public/NOTES/notes/AN-14-290/trunk/Plots/v1.0/", std::string ext="png") {
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  
  bool latex = save;
  
  bool ABCD_prime = 0;
  bool TT_only = 0;
  
  std::stringstream ss, ss2;
  ss<<DPHI_CUT; ss2<<R_CUT;
  std::string dphi_cut = ss.str().replace(ss.str().find("."),1,"p");
  std::string r_cut = ss2.str().replace(ss2.str().find("."),1,"p");
  
  std::string filename = in.size() ? in : 
    //"results/Plotter_out_2016_05_31_08h48m57_replot.root";
    "results/Plotter_out_2016_06_24_14h28m51.root";
  
  std::vector<std::string> samples[4];
  //samples[0].push_back("TTJetsMGHT");
  //samples[0].push_back("TTJetsMG");
  //samples[0].push_back("TTJetsNLOFXFX");
  //samples[0].push_back("TTNLO");
  //samples[0].push_back("TTNLOHerwig");
  //samples[0].push_back("TTPowheg");
  //samples[0].push_back("TTPowhegmpiOff");
  //samples[0].push_back("TTPowhegnoCR");
  //samples[0].push_back("TTPowhegHerwig");
  
  //+data+ samples[1].push_back("SingleElectron");
  //+data+ samples[1].push_back("SingleMuon");
  if (TT_only) {
    samples[1].push_back("TTJetsMGHT");
    samples[1].push_back("TTJetsMG");
    samples[1].push_back("TTJetsNLOFXFX");
    samples[1].push_back("TTNLO");
    samples[1].push_back("TTNLOHerwig");
    samples[1].push_back("TTPowheg");
    samples[1].push_back("TTPowhegmpiOFF");
    samples[1].push_back("TTPowhegnoCR");
    samples[1].push_back("TTPowhegHerwig");
  } else {
    samples[1].push_back("TTJetsMGHT");
    //samples[1].push_back("TTJetsMG");
    //samples[1].push_back("TTJetsNLOFXFX");
    //samples[1].push_back("TTNLO");
    //samples[1].push_back("TTNLOHerwig");
    //samples[1].push_back("TTPowheg");
    //samples[1].push_back("TTPowhegmpiOff");
    //samples[1].push_back("TTPowhegnoCR");
    //samples[1].push_back("TTPowhegHerwig");
    samples[1].push_back("ZJets");
    samples[1].push_back("TTX");
    samples[1].push_back("WJets");
    samples[1].push_back("Diboson");
    samples[1].push_back("Top");
    samples[1].push_back("QCD");
    //ZERO samples[1].push_back("TZQ");
    //ZERO samples[1].push_back("ZJetsToQQ"); // Also WJetsToQQ
    //ZERO samples[1].push_back("GJets");
  }
  //samples[1].push_back("Data");
  // NTop Sideband All background summed
  samples[2].push_back("All Bkg.");
    
  // Signal in NTop bins
  samples[3].push_back("T1tttt");
  
  bool baderror = false;
  double weight[] = { 0.32686, 0.0505037, 0.00921411, 6.80717, 0.354934, 0.00484915 };
  int rebin = /*(R_CUT*10-int(R_CUT*10))==0 ? 10 :*/ (R_CUT*20-int(R_CUT*20))==0 ? 5 : (R_CUT*50-int(R_CUT*50))==0 ? 2 : 1;
  double sideband_fit_low_range[] = { 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15 };
  
  int i_h_side[]   = { 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  int i_h_signal[] = { 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
  
  double scale_factors[] = { 1, 1, 1, 1, 1, 1, 1}; // All normal
  //double scale_factors[] = { /* TT */ 1, /* W */ 1, /* Z */ 1, /* T */ 1, /* TTV */ 1, /* QCD */ 2, /* VV */ 1 }; // QCD high
  //double scale_factors[] = { /* TT */ 5, /* W */ 1, /* Z */ 1, /* T */ 1, /* TTV */ 5, /* QCD */ 1, /* VV */ 1 }; // TT/TTV high
  //double scale_factors[] = { /* TT */ 1, /* W */ 2, /* Z */ 2, /* T */ 2, /* TTV */ 1, /* QCD */ 1, /* VV */ 2 }; // T/V/VV high
  
  Double_t Rranges_ABCD[][4] = 
    { { DPHI_CUT, 3.2, 0.0, DPHI_CUT  },
      { R_CUT_LOW-1e-10, R_CUT, R_CUT-1e-10, 1.20 },
      { R_CUT_LOW-1e-10, R_CUT, R_CUT-1e-10, 1.20 },
      { R_CUT_LOW-1e-10, R_CUT, R_CUT-1e-10, 1.20 } };
  bool doFitting = false;
  double sum_a = 0, sum_b = 0, sum_c = 0, sum_d = 0, sum_d_abcd = 0, sum_d_nevt = 0;
  double sum_a_err = 0, sum_b_err = 0, sum_c_err = 0, sum_d_err = 0, sum_d_abcd_err = 0;
  double sum_b_fit = 0, sum_d_fit = 0, sum_d_fit_comb = 0;
  double sum_b_fit_err = 0, sum_d_fit_err = 0, sum_d_fit_comb_err = 0;
  double comb_d = 0, comb_d_err = 0, comb_d_abcd = 0, comb_d_abcd_err = 0;
  if (latex) {
    printf("\\begin{table*}[htbH]\n");
    printf("\\small\n");
    printf("\\begin{center}\n");
    printf("\\topcaption{Estimated Standard Model background yields in ABCD regions. A, B is in the sideband, C and D is the signal band, D is the signal region.\\label{tab:SMBkgEstimate}}\n");
    printf("\\begin{tabular}{lrrrrrrrr}\n");
  }
  TFile *f = TFile::Open(filename.c_str());
  for (size_t iMethod = 0; iMethod<4; ++iMethod) if (!(iMethod==0&&samples[0].size()==0)){
    // Print Top row for each method
    if (latex) {
      if (iMethod==0) {
        printf("\\hline\n");
        printf("Method 2 & A & B & C & D = B*C/A & D obs. & Ratio pred./obs. & Pull & KS test\\\\\n");
      }	else if (iMethod==1){
        printf("\\hline\n");
        printf("Method 1 & A & B & C & D = B*C/A & D obs. & Ratio pred./obs. & Pull & KS test\\\\\n");
      }
      printf("\\hline\n");
    } else {
      std::stringstream r_sb_cut;
      if (R_CUT_LOW==0) r_sb_cut<<"R<"<<R_CUT;
      else r_sb_cut<<R_CUT_LOW<<"<R<"<<R_CUT;
      const char* prime = ABCD_prime ? "'" : "";
      //if (iMethod==0) printf("| *Sample* | *A (DPhi>2.8, SB)* | *B (DPhi<2.8, SB)* | *C (DPhi>2.8, Sig.B.)* | - | *D = B*C/A pred.* | *D (DPhi<2.8, Sig.B.) obs.* | *Ratio pred./obs.* |\n");
      //else if (iMethod==1) printf("| *Sample* | *A (R<%1.1f, SB)* | *B (R>%1.1f, SB)* | *C (R<%1.1f, Sig.B.)* | *D = B (R fit, SB) * C/A pred.* | *D = B*C/A pred.* | *D (R>%1.1f, Sig.B.) obs.* | *Ratio pred./obs.* | \n", R_CUT, R_CUT, R_CUT, R_CUT);
      if (iMethod==0) printf("| *Sample* | *A (DPhi>%1.1f, %s)* | *B (DPhi<%1.1f, %s)* | *C (DPhi>%1.1f, R>0.4)* | *D = B*C/A pred.* | *D (DPhi<%1.1f, R>0.4) obs.* | *Ratio pred./obs.* | *Pull (pred-obs)/error* | *KS test* |\n", DPHI_CUT, r_sb_cut.str().c_str(), DPHI_CUT, r_sb_cut.str().c_str(), DPHI_CUT, DPHI_CUT);
      else if (iMethod==1) printf("| *Sample* | *A%s (%s, <2 tag)* | *B%s (R>%1.1f, <2 tag)* | *C%s (%s, 2 tag)* | *D%s = B%s*C%s/A%s pred.* | *D%s (R>%1.1f, 2 tag) obs.* | *Ratio pred./obs.* | *Pull (pred-obs)/error* | *KS test* |\n", prime, r_sb_cut.str().c_str(), prime, R_CUT, prime, r_sb_cut.str().c_str(), prime, prime, prime, prime, prime, R_CUT);
    }
    TH1D *h_side_sum, *h_signal_sum;
    for (size_t iSample = 0; iSample<samples[iMethod].size(); ++iSample)  {
      std::string canname = 
	iMethod==0 ? std::string("DPhiBins")+(ABCD_prime ? "/RBins_0To1HadTop_" : "/RBins_2HadTop_")+samples[iMethod][iSample] :
	iMethod==1 ? std::string("RFine/Tau32Cuts_")+(ABCD_prime ? "Fail" : "Pass")+"DPhiCut_"+samples[iMethod][iSample] :
	iMethod==2 ? std::string("RFine/Tau32Cuts_")+(ABCD_prime ? "Fail" : "Pass")+"DPhiCut_Background" :
	iMethod==3 ? std::string("RFine/Tau32Cuts_")+(ABCD_prime ? "Fail" : "Pass")+"DPhiCut_"+samples[iMethod][iSample] : "";
      TCanvas *can = (TCanvas*)(f->Get(canname.c_str()));
      can = (TCanvas*)can->Clone();
      can->Draw();
      TH1D *h_side = (TH1D*)can->GetListOfPrimitives()->At(i_h_side[iMethod]);
      TH1D *h_signal = (TH1D*)can->GetListOfPrimitives()->At(i_h_signal[iMethod]);
      // Simulate different cross section by scaling a certain background
      if (iMethod==1) {
        TH1D *h_side_temp_scaled = (TH1D*)h_side->Clone(); h_side_temp_scaled->Scale(scale_factors[iSample]);
        TH1D *h_signal_temp_scaled = (TH1D*)h_signal->Clone(); h_signal_temp_scaled->Scale(scale_factors[iSample]);
        if (iSample==0) {
          h_side_sum = h_side_temp_scaled;
          h_signal_sum = h_signal_temp_scaled;
        } else {
          h_side_sum->Add(h_side_temp_scaled);
          h_signal_sum->Add(h_signal_temp_scaled);
        }
      } else if (iMethod==2) {
        h_side = h_side_sum;
        h_signal = h_signal_sum;
      }
      TH1D *h_pred =(TH1D*)h_side->Clone();
      if (iMethod!=0&&rebin>1) { h_side->Rebin(rebin); h_signal->Rebin(rebin); h_pred->Rebin(rebin); }
      TLegend *leg = (TLegend*)can->GetListOfPrimitives()->At(can->GetListOfPrimitives()->GetEntries()-1);
      leg->SetX1(0.35); leg->SetX2(0.65); leg->SetY1(0.6);
      
      // Add ratio plot
      int y1 = 350;
      int y2 = 150;
      int mid2 = 10;
      can->Divide(1,2);
      // Pad 1 (80+500+20 x 40+500)
      TVirtualPad* p = can->cd(1);
      p->SetPad(0,(y2+60+mid2)/(y1+y2+100.0+mid2),1,1);
      p->SetTopMargin(40.0/(y1+40));
      p->SetBottomMargin(0);
      p->SetRightMargin(0.05);
      p->SetLogy(1);
      h_side->GetYaxis()->SetRangeUser(1.00001e-4,1e4);
      h_side->Draw("HIST");
      h_signal->Draw("SAMEHISTE1");
      leg->Draw();
      // Pad 2 (80+500+20 x 200+60)
      p = can->cd(2);
      p->SetGrid(0,1);
      p->SetPad(0,0,1,(y2+60+mid2)/(y1+y2+100.0+mid2));
      p->SetTopMargin(((float)mid2)/(y2+60+mid2));
      p->SetBottomMargin(60.0/(y2+60+mid2));
      p->SetRightMargin(0.05);
      TH1D* ratio = (TH1D*)h_signal->Clone();
      TH1D* div = (TH1D*)h_side->Clone();
      //ratio->Scale(1/ratio->GetSumOfWeights());
      double sum_bins_ratio = iMethod==0 ? ratio->Integral():
	ratio->Integral(ratio->FindBin(R_CUT_LOW),ratio->FindBin(Rranges_ABCD[iMethod][3]));
      ratio->Scale(1/sum_bins_ratio);
      ratio->SetTitleSize(32.0/(y2+60+mid2),"xyz");
      ratio->SetLabelSize(20.0/(y2+60+mid2),"xyz");
      //ratio->Scale(1/div->GetSumOfWeights());
      double sum_bins_div = iMethod==0 ? div->Integral():
	div->Integral(div->FindBin(R_CUT_LOW),div->FindBin(Rranges_ABCD[iMethod][3]));
      div->Scale(1/sum_bins_div);
      ratio->Divide(div);
      //ratio->GetYaxis()->SetRangeUser(0,2);
      ratio->GetXaxis()->SetTitleOffset(0.7);
      ratio->GetYaxis()->SetNdivisions(305);
      ratio->GetYaxis()->SetTitle("Ratio (Norm.)");
      ratio->GetYaxis()->SetTitleOffset(0.4);
      ratio->SetTitleSize(24.0/(y2+60+mid2),"y");
      ratio->SetTitle("");
      ratio->SetMarkerStyle(20);
      ratio->SetMarkerColor(1);
      ratio->SetLineColor(1);
      ratio->GetYaxis()->SetRangeUser(0,4);
      ratio->Draw("PE1");
      TLine* l = new TLine(ratio->GetXaxis()->GetXmin(), 1, ratio->GetXaxis()->GetXmax(), 1);
      l->SetLineWidth(2);
      //l->SetLineColor(2);
      l->SetLineStyle(2);
      l->Draw();
      gPad->Update();
      // Fit ratio
      //TF1 *fit_ratio;
      //if (iMethod==1) {
      //  fit_ratio = new TF1("fit_ratio","pol0", Rranges_ABCD[iMethod][0], Rranges_ABCD[iMethod][1]);
      //  fit_ratio->SetLineColor(1);
      //  ratio->Fit("fit_ratio","RE");
      //  fit_ratio->SetRange(Rranges_ABCD[iMethod][0], Rranges_ABCD[iMethod][2]);
      //  fit_ratio->Draw("SAME");
      //}
      p = can->cd(1);
      
      // calculate integrals
      double integral[2][2] = { { 0, 0 }, { 0, 0 } };
      double integral_error[2][2] = { { 0, 0 }, { 0, 0 } };
      double nevt[2][2] = { { 0, 0 }, { 0, 0 } };
      //std::cout<<samples[iMethod][iSample]<<":"<<std::endl;
      for (int i=0; i<2; ++i) {
        for (int bin=1; bin<=h_side->GetNbinsX(); ++bin) {
          if (h_signal->GetXaxis()->GetBinLowEdge(bin)>=Rranges_ABCD[iMethod][i*2] && 
              h_signal->GetXaxis()->GetBinUpEdge(bin)<=Rranges_ABCD[iMethod][i*2+1]) {
	    //std::cout<<bin<<"="<<h_side->GetBinCenter(bin);
	    //if (i==0) std::cout<<" in, ";
	    //else std::cout<<" out, ";
            double c0 = h_side->GetBinContent(bin), c1 = h_signal->GetBinContent(bin);
            double e0 = h_side->GetBinError(bin),   e1 = h_signal->GetBinError(bin);
            //std::cout<<h_signal->GetBinError(bin)<<" "<<sqrt(c1*weight[iSample])<<std::endl;
            if (baderror&&iMethod==1) {
              e0 = sqrt(c0*weight[iSample]);
              e1 = sqrt(c1*weight[iSample]);
            }
            nevt[0][i] += (int)(c0*c0/(e0*e0) + 0.5);
            nevt[1][i] += (int)(c1*c1/(e1*e1) + 0.5);
            integral[0][i] += c0;
            integral[1][i] += c1;
            //if (iMethod==1) { // weight bin by projected ratio (correction)
            //  double bincent = h_signal->GetXaxis()->GetBinLowEdge(bin);
            //  integral[0][1] *= fit_ratio->Eval(bincent);
            //}
            integral_error[0][i] += e0*e0;
            integral_error[1][i] += e1*e1;
            //if (iSample==0&&e1>0) std::cout<<bin<<" "<<c1<<" +- "<<e1*e1<<" nevt = "<<((int)(c1*c1/(e1*e1) + 0.5))<<std::endl;
          }
        }
        //if (iSample==1&&i==1) std::cout<<integral[1][i]<<" +- "<<integral_error[1][i]<<std::endl;
        integral_error[0][i] = sqrt(integral_error[0][i]);
        integral_error[1][i] = sqrt(integral_error[1][i]);
      }
      //std::cout<<nevt[1][1]<<std::endl;
      
      // predict yields using 2 methods (ABCD and constrained R-shape fit method combined)
      // ABCD method
      double a = integral[0][0], b = integral[0][1], c = integral[1][0], d = integral[1][1];
      double a_err = integral_error[0][0], b_err = integral_error[0][1], c_err = integral_error[1][0], d_err = integral_error[1][1];
      // Calculate error
      // z = x / y -> z_err = sqrt( (x*x*y_err*y_err + y*y*x_err*x_err)/(y*y*y*y) )
      // z = x * y -> z_err = sqrt ( x*x*y_err*y_err + y*y*x_err*x_err )
      double c_per_a_err = sqrt((c*c*a_err*a_err + a*a*c_err*c_err)/(a*a*a*a));
      double d_abcd = b * (c/a), d_abcd_err = sqrt(b*b*c_per_a_err*c_per_a_err + (c/a)*(c/a)*b_err*b_err);
      double d_nevt = nevt[1][1];
      double d_ratio = d_abcd / d;
      double d_ratio_err = sqrt((d_err/d)*(d_err/d) + (d_abcd_err/d_abcd)*(d_abcd_err/d_abcd))*d_ratio;
      double d_pull = (d_abcd-d)/sqrt(d_abcd_err*d_abcd_err + d_err*d_err);
      // Scaled plot
      h_pred->Scale(c/a);
      h_pred->SetLineColor(1);
      h_pred->SetLineStyle(2);
      h_pred->Draw("SAMEHIST");
      leg->AddEntry(h_pred, "Prediction (ABCD)", "l");
      
      double fit_integral[2][2], fit_integral_error[2][2], d_fit_comb = 0, d_fit_comb_err = 0;
      if (iMethod==1) {
	// Fit in the full range of NTop Sideband
	// Do fitting and calculate integrals
	TF1 *fit_side = new TF1("NTopSide_fit","exp([0]+[1]*x)", iMethod==2 ? 0.2 : sideband_fit_low_range[iSample], Rranges_ABCD[iMethod][3]);
        fit_side->SetLineColor(h_side->GetLineColor());
        h_side->Fit("NTopSide_fit","QRE");
        //fit_side->Draw("SAME");
        double Rranges_ACfit[3] = { sideband_fit_low_range[iSample], Rranges_ABCD[iMethod][2], Rranges_ABCD[iMethod][3] };
        for (int i=0; i<2; ++i) {
          fit_integral[0][i] = fit_side->Integral(Rranges_ACfit[i], Rranges_ACfit[i+1])/h_signal->GetXaxis()->GetBinWidth(1);
          fit_integral_error[0][i] = fit_side->IntegralError(Rranges_ACfit[i], Rranges_ACfit[i+1])/h_signal->GetXaxis()->GetBinWidth(1);
        }
        double par0 = fit_side->GetParameter(0), par0_error = fit_side->GetParError(0);
        double par1 = fit_side->GetParameter(1), par1_error = fit_side->GetParError(1);
        double par1min, par1max; fit_side->GetParLimits(1, par1min, par1max);
	
        // Fit in the Signal region
        // Fitting in sideband, get B area under curve and scale by C/A
        TF1 *fit_signal = new TF1("NTopSignal_RSide_fit","exp([0]+[1]*x)", Rranges_ACfit[0], Rranges_ABCD[iMethod][3]);
        fit_signal->SetLineColor(h_signal->GetLineColor());
        //fit_signal->SetParameter(1, par1); 
        //fit_signal->SetParLimits(1, par1min, par1max);
        h_signal->Fit("NTopSignal_RSide_fit","QREB");
        //fit_signal->Draw("SAME");
        for (int i=0; i<2; ++i) {
          fit_integral[1][i] = fit_signal->Integral(Rranges_ACfit[i], Rranges_ACfit[i+1])/h_signal->GetXaxis()->GetBinWidth(1);
          fit_integral_error[1][i] = fit_signal->IntegralError(Rranges_ACfit[i], Rranges_ACfit[i+1])/h_signal->GetXaxis()->GetBinWidth(1);
        }
        d_fit_comb = fit_integral[0][1] * (c/a);
        d_fit_comb_err = sqrt(fit_integral[0][1]*fit_integral[0][1]*c_per_a_err*c_per_a_err + (c/a)*(c/a)*fit_integral_error[0][1]*fit_integral_error[0][1]);
        TF1 *fit_pred = new TF1("Predicted_fit","exp([0]+[1]*x)", Rranges_ACfit[0], Rranges_ACfit[2]);
        fit_pred->SetLineColor(1);
        fit_pred->SetLineStyle(2);
        fit_pred->FixParameter(0, par0+std::log(c/a)); 
        fit_pred->FixParameter(1, par1); 
        h_signal->Fit("Predicted_fit","QREB+");
        //fit_pred->Draw("SAME");
      }
      // Save plot
      if (iMethod==3) samples[iMethod][iSample] = "T1tttt";
      std::string name = samples[iMethod][iSample];
      if (iMethod==2) name = "AllBkg";
      if (save)	can->SaveAs((out+"BkgEst/ABCD_closure_"+name+"."+ext).c_str());
      
      // Check compatibility of prediction to observed distribution
      double ks_test = h_pred->KolmogorovTest(h_signal);
      
      if (iMethod==1) {
	sum_a += a; sum_b += b; sum_c += c; sum_d += d;
	sum_a_err += a_err*a_err; sum_b_err += b_err*b_err; sum_c_err += c_err*c_err; sum_d_err += d_err*d_err;
	sum_d_abcd += d_abcd; sum_d_abcd_err += d_abcd_err*d_abcd_err;
	sum_b_fit += fit_integral[0][1]; sum_b_fit_err += fit_integral_error[0][1]*fit_integral_error[0][1];
	sum_d_fit += fit_integral[1][1]; sum_d_fit_err += fit_integral_error[1][1]*fit_integral_error[1][1];
	sum_d_fit_comb += d_fit_comb; sum_d_fit_comb_err += d_fit_comb_err*d_fit_comb_err;
	sum_d_nevt += d_nevt;
	//printf("  %.2f +- %.2f |  %.2f +- %.2f |  %.2f +- %.2f |  %.2f +- %.2f |\n", d_fit_comb, d_fit_comb_err, d_abcd, d_abcd_err, d, d_err, d_ratio, d_ratio_err);
      }
      if (latex) {
	printf("%s &  $%.2f \\pm %.2f$ &  $%.2f \\pm %.2f$ &  $%.2f \\pm %.2f$ &", samples[iMethod][iSample].c_str(), a, a_err, b, b_err, c, c_err);
	printf("  $%.2f \\pm %.2f$ &  $%.2f \\pm %.2f$ &  $%.2f \\pm %.2f$ &  %.2f &  %.2f \\\\\n", d_abcd, d_abcd_err, d, d_err, d_ratio, d_ratio_err, d_pull, ks_test);
      } else {
	printf("| %s |  %.2f +- %.2f |  %.2f +- %.2f |  %.2f +- %.2f |", samples[iMethod][iSample].c_str(), a, a_err, b, b_err, c, c_err);
	printf("  %.2f +- %.2f |  %.2f +- %.2f |  %.2f +- %.2f |  %.2f |  %.2f |\n", d_abcd, d_abcd_err, d, d_err, d_ratio, d_ratio_err, d_pull, ks_test);
      }
      // Combining best methods
      if ((iMethod==0&&iSample==0)||(iMethod==1&&iSample!=0)) {
	comb_d_abcd += d_abcd; comb_d += d; comb_d_abcd_err += d_abcd_err*d_abcd_err; comb_d_err += d_err*d_err;
      }
    }
    if (iMethod==1) {
      sum_a_err = sqrt(sum_a_err); sum_b_err = sqrt(sum_b_err); sum_c_err = sqrt(sum_c_err); sum_d_err = sqrt(sum_d_err);
      sum_b_fit_err = sqrt(sum_b_fit_err); sum_d_fit_err = sqrt(sum_d_fit_err); sum_d_fit_comb_err = sqrt(sum_d_fit_comb_err);
      double sum_d_ratio = sum_d_abcd / sum_d;
      double sum_d_ratio_err = sqrt((sum_d_err/sum_d)*(sum_d_err/sum_d) + (sum_d_abcd_err/sum_d_abcd)*(sum_d_abcd_err/sum_d_abcd))*sum_d_ratio;
      double sum_d_pull = (sum_d_abcd-sum_d)/sqrt(sum_d_abcd_err*sum_d_abcd_err + sum_d_err*sum_d_err);
      if (latex) {
	printf("\\hline\n");
	printf("Sum Bkg. &  $%.2f \\pm %.2f$ &  $%.2f \\pm %.2f$ &  $%.2f \\pm %.2f$ &", sum_a, sum_a_err, sum_b, sum_b_err, sum_c, sum_c_err);
	printf("  $%.2f \\pm %.2f$ &  $%.2f \\pm %.2f$ &  $%.2f \\pm %.2f$ &  %.2f & \\\\\n", sum_d_abcd, sum_d_abcd_err, sum_d, sum_d_err, sum_d_ratio, sum_d_ratio_err, sum_d_pull);
      } else {
	//printf("| Sum Bkg.|  %.2f +- %.2f |  %.2f +- %.2f |  %.2f +- %.2f |  %.2f +- %.2f |", sum_a, sum_a_err, sum_b_fit, sum_b_fit_err, sum_b, sum_b_err, sum_c, sum_c_err);
	printf("| Sum Bkg.|  %.2f +- %.2f |  %.2f +- %.2f |  %.2f +- %.2f |", sum_a, sum_a_err, sum_b, sum_b_err, sum_c, sum_c_err);
	//printf("  %.2f +- %.2f |  %.2f +- %.2f |  %.2f +- %.2f |  %.2f +- %.2f |\n", sum_d_fit_comb, sum_d_fit_comb_err, sum_d_abcd, sum_d_abcd_err, sum_d, sum_d_err, sum_d_ratio, sum_d_ratio_err);
	printf("  %.2f +- %.2f |  %.2f +- %.2f |  %.2f +- %.2f |  %.2f |  - |\n", sum_d_abcd, sum_d_abcd_err, sum_d, sum_d_err, sum_d_ratio, sum_d_ratio_err, sum_d_pull);
      }
    } else if (iMethod==2&&samples[0].size()) {
      double comb_d_ratio = comb_d_abcd / comb_d;
      double comb_d_ratio_err = sqrt((comb_d_err/comb_d)*(comb_d_err/comb_d) + (comb_d_abcd_err/comb_d_abcd)*(comb_d_abcd_err/comb_d_abcd))*comb_d_ratio;
      double comb_d_pull = (comb_d_abcd-comb_d)/sqrt(comb_d_abcd_err*comb_d_abcd_err + comb_d_err*comb_d_err);
      if (latex) {
	printf("\\hline\n");
	printf("\\hline\n");
	printf("Combined Bkg. & & & &  $%.2f \\pm %.2f$ &  $%.2f \\pm %.2f$ &  $%.2f \\pm %.2f$ &  %.2f & \\\\\n", comb_d_abcd, comb_d_abcd_err, comb_d, comb_d_err, comb_d_ratio, comb_d_ratio_err, comb_d_pull);
	printf("\\hline\n");
      } else {
	printf("| Combined Bkg.| | | |  %.2f +- %.2f |  %.2f +- %.2f |  %.2f +- %.2f |  %.2f | - |\n", comb_d_abcd, comb_d_abcd_err, comb_d, comb_d_err, comb_d_ratio, comb_d_ratio_err, comb_d_pull);
      }
    }
  }
  if (latex) {
    printf("\\hline\n");
    printf("\\end{tabular}\n");
    printf("\\end{center}\n");
    printf("\\end{table*}\n");
  }

  if (save) gApplication->Terminate();
}