#include "TCanvas.h"
#include "TROOT.h"
#include "TFile.h"
#include "TTree.h"
#include "TBrowser.h"
#include "TH2.h"
#include "TRandom.h"

void tree1r()
{
  // Open the root file  Selected_All_EEM.root file (data)
  TFile *f = new TFile("Selected_All_EEM.root");

  // Get the Tree named "WZSignal" (Signal events), instance(pointer) called 'sig'
  TTree *sig = (TTree*)f->Get("WZSignal");
    
  // Define variables
  Double_t pt1, eta1, phi1, E1;
  Double_t pt2, eta2, phi2, E2;
  Double_t pt3, eta3, phi3, E3;
  Double_t MZ, MET, trackd0cutWMu, TrackIsoWmu;
  Double_t Weight;

    //extract some variables for SIGNAL EVENTS (NOTE: the first argument is the name of the variable)
  sig->SetBranchAddress("pt1",&pt1);
  sig->SetBranchAddress("eta1",&eta1);
  sig->SetBranchAddress("phi1",&phi1);
  sig->SetBranchAddress("E1",&E1);
  sig->SetBranchAddress("MZ",&MZ);
  sig->SetBranchAddress("Weight",&Weight); 
  // add other variables for particle 2,3 etcc.. look at the text of the exercise


  // Get the Tree named "ttbar" (background), instance(pointer) called 'ttbar'
  TTree *ttbar = (TTree*)f->Get("ttbar");
    
    // Define variables
  Double_t pt1_bkg, eta1_bkg, phi1_bkg, E1_bkg;
  Double_t MZ_bkg;
  Double_t Weight_bkg;

  ///extract some variables for backgroung  EVENTS (NOTE: the first argument is the name of the variable)
  ttbar->SetBranchAddress("pt1",&pt1_bkg);
  ttbar->SetBranchAddress("eta1",&eta1_bkg);
  ttbar->SetBranchAddress("phi1",&phi1_bkg);
  ttbar->SetBranchAddress("E1",&E1_bkg);
  ttbar->SetBranchAddress("MZ",&MZ_bkg);
  ttbar->SetBranchAddress("Weight",&Weight_bkg); 
// add other variables for particle 2,3 etcc.. look at the text of the exercise

  //create  histograms (the first for all events the 2nd and 3rd for sig and ttbar)
  TH1F *h_MZ       = new TH1F("h_MZ","MZ distribution All events",40,65,115);
  TH1F *h_MZ_bkg   = new TH1F("h_MZ_bkg","MZ distribution BKG",40,65,115);
  TH1F *h_MZ_sig   = new TH1F("h_MZ_sig","MZ distribution SIG",40,65,115);  

  //Get the number of events in SIGNAL Tree
  Int_t nentries = (Int_t)sig->GetEntries();
  
    //Loop on all SIGNAL entries and fill the histograms
  for (Int_t i=0;i<nentries;i++) {
    sig->GetEntry(i);
    h_MZ->Fill(MZ,Weight);
    h_MZ_sig->Fill(MZ,Weight);
  }

 //Get the number of events in backgorund Tree
  Int_t nentries_bkg = (Int_t)ttbar->GetEntries();
  
    //Loop on all BKG entries and fill the histograms
  for (Int_t i=0;i<nentries_bkg;i++) {
    ttbar->GetEntry(i);
    h_MZ_bkg->Fill(MZ_bkg,Weight_bkg);
    h_MZ->Fill(MZ_bkg,Weight);
  }
  
  // example how Draw and  save histograms
    
  TCanvas *c = new TCanvas(); // Define a canvas
  c->cd();                    // move to this canvas
  h_MZ_sig->Draw();           // Plot the histo
  h_MZ_bkg->SetLineColor(kRed);
  h_MZ_bkg->Draw("same");
  
  c->Print("test_MZ.pdf");   // Print the histogram
}   

void macro() 
{
  tree1r();
}
