//void  EnergyFlow_DetLevel_TreeProducer(int FileNumber=0)
void  EnergyFlow_DetLevel_DataZeroBias1AllBx_TreeProducer()

{
  gROOT->ProcessLine("#include <vector>"); 
  //gROOT->ProcessLine(".L MC.C+");
  //setTDRStyle();
    
  gDirectory->DeleteAll();
  gROOT->ForceStyle();
  gStyle->SetOptFit(0);
  gStyle->SetOptStat(0); 
    
  cout<<"file dir :   "<<readfilesdir.c_str()<<"     file number : "<<readfilesnumber_in_dir<<endl;
  static const Int_t ftyp =1;
  static const Int_t fnumber =readfilesnumber_in_dir ;

  //string fname[6]={"Data","herwigpp","pythia8_Monash","pythia8_MBR","epos","qgsjetII"};
  for (int i=0; i<ftyp;i++){
    cout << " file :"<<i<<" ==> "<<filetype.c_str()<<endl;
  };
  //gStyle->SetOptStat(111);
  bool save =true;
  string filenames ="";
  string energyname[15]={"RecHitHCAL","RecHitHF","RecHitECAL","CaloTower",
			 "hcalPFClustersCorrEnergy","ecalPFClustersCorrEnergy","HFPFClustersCorrEnergy",
			 "hcalPFClustersRawEnergy","ecalPFClustersRawEnergy","HFPFClustersRawEnergy",
			 "Gen","Events","CastorTower","CastorRecHit","PFCandidate"};
    
    
   
    
    
  static const Int_t etyp = 15 ;
   
  char title[999];
  
  vector<float> RecHitHCAL; 
  vector<float> RecHitHF;
  vector<float> RecHitECAL; 
  vector<float> RecHit;
  vector<float> CaloTower;
  vector<float> HCALTower;
  vector<float> SDHFSignalTower;  //New Part
  vector<float> SDHFVetoTower;    //New Part
  vector<float> hcalPFClustersCorrEnergy; 
  vector<float> ecalPFClustersCorrEnergy;
  vector<float> HFPFClustersCorrEnergy;
  vector<float> hcalPFClustersRawEnergy;
  vector<float> ecalPFClustersRawEnergy;
  vector<float> HFPFClustersRawEnergy;
  vector<float> PFClusters;
  vector<float> GenDetEventSelect;
  vector<float> CastorTower;
  vector<float> RecHitCastor; 
  vector<float> PFCandidate;

  TFile *fOutFile[ftyp+1];
  TTree *EnergyFlow_Det[ftyp+1];
  int TotNofEvent[ftyp+1];
    
  TTree *fChain[fnumber+1];
  TFile *file[fnumber+1];

  int decade = 0;

  float Norm=1.0;
  if (filetype=="MC") Norm=1.0/1.117;
  else Norm=Norm;

  for (int f=0; f<ftyp; f++){
    //for (int f=FileNumber; f<FileNumber+1; f++){
    //----------------------Creating tree for output--------------//
    sprintf(title,"EFlow_DetLevel_%s_JINSTBinning_SDEnhanced_NoiseCut4GeV_Emin5GeV.root",readfilesname.c_str());
    fOutFile[f]= new TFile(title,"RECREATE");
    //sprintf(title,"%s",fname.c_str());
    sprintf(title,"EFlow");
    EnergyFlow_Det[f]= new TTree(title,title);
    EnergyFlow_Det[f]->Branch("RecHitHCAL",&RecHitHCAL); 
    EnergyFlow_Det[f]->Branch("RecHitHF",&RecHitHF);
    EnergyFlow_Det[f]->Branch("RecHitECAL",&RecHitECAL); 
    EnergyFlow_Det[f]->Branch("CaloTower",&CaloTower);
    EnergyFlow_Det[f]->Branch("SDHFSignalTower",&SDHFSignalTower);//New Part
    EnergyFlow_Det[f]->Branch("SDHFVetoTower",&SDHFVetoTower);//New Part
    EnergyFlow_Det[f]->Branch("HCALTower",&HCALTower);
    EnergyFlow_Det[f]->Branch("RecHit",&RecHit);
    EnergyFlow_Det[f]->Branch("hcalPFClustersCorrEnergy",&hcalPFClustersCorrEnergy); 
    EnergyFlow_Det[f]->Branch("ecalPFClustersCorrEnergy",&ecalPFClustersCorrEnergy);
    EnergyFlow_Det[f]->Branch("HFPFClustersCorrEnergy",&HFPFClustersCorrEnergy);
    EnergyFlow_Det[f]->Branch("hcalPFClustersRawEnergy",&hcalPFClustersRawEnergy);
    EnergyFlow_Det[f]->Branch("ecalPFClustersRawEnergy",&ecalPFClustersRawEnergy);
    EnergyFlow_Det[f]->Branch("HFPFClustersRawEnergy",&HFPFClustersRawEnergy);
    EnergyFlow_Det[f]->Branch("PFClusters",&PFClusters);
    EnergyFlow_Det[f]->Branch("GenDetEventSelect",&GenDetEventSelect);
    EnergyFlow_Det[f]->Branch("CastorTower",&CastorTower);
    EnergyFlow_Det[f]->Branch("RecHitCastor",&RecHitCastor);
    EnergyFlow_Det[f]->Branch("PFCandidate",&PFCandidate);

    TotNofEvent[f]= 0;
    //------- File Number ---------//                                                                                                                                                
    for (int fn=0; fn < fnumber ; fn++){
      // --- open file in EOS                                                                                                                                                      
      char Fname[999];
      sprintf(Fname,"trees_%d.root",(fn+1));
      string sFname(Fname);
      string filenames=readfilesdir+sFname;
      cout<<"file : "<<filenames.c_str()<<endl;
      file[fn]   = TFile::Open(filenames.c_str(),"READ");
	    
      // --- read tree
      fChain[fn] = (TTree*)file[fn]->Get("EflowTree/data");
      //Event
      fChain[fn]->SetBranchAddress("run", &run, &b_run);
      fChain[fn]->SetBranchAddress("lumi", &lumi, &b_lumi);
      fChain[fn]->SetBranchAddress("event", &event, &b_event);
      fChain[fn]->SetBranchAddress("genWeight", &genWeight, &b_genWeight);
      fChain[fn]->SetBranchAddress("processID", &processID, &b_processID);
      fChain[fn]->SetBranchAddress("cmenergy", &cmenergy, &b_cmenergy);
      fChain[fn]->SetBranchAddress("puTrueNumInteractions", &puTrueNumInteractions, &b_puTrueNumInteractions);
      fChain[fn]->SetBranchAddress("PUNumInteractions", &PUNumInteractions, &b_PUNumInteractions);
	    
      std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * genParticlesp4_ = 0;
      if(filetype =="MC"){
	fChain[fn]->SetBranchAddress("genParticlesp4", &genParticlesp4_);
	fChain[fn]->SetBranchAddress("genParticlescharge", &genParticlescharge, &b_genParticlescharge);
	fChain[fn]->SetBranchAddress("genParticlespdg", &genParticlespdg, &b_genParticlespdg);
	fChain[fn]->SetBranchAddress("genParticlesstatus", &genParticlesstatus, &b_genParticlesstatus);
	fChain[fn]->SetBranchAddress("Xix", &Xix, &b_Xix);
	fChain[fn]->SetBranchAddress("Xiy", &Xiy, &b_Xiy);
	fChain[fn]->SetBranchAddress("XiSD", &XiSD, &b_XiSD);
	fChain[fn]->SetBranchAddress("XiDD", &XiDD, &b_XiDD);
      }
      fChain[fn]->SetBranchAddress("vtxx", &vtxx, &b_vtxx);
      fChain[fn]->SetBranchAddress("vtxy", &vtxy, &b_vtxy);
      fChain[fn]->SetBranchAddress("vtxz", &vtxz, &b_vtxz);
      fChain[fn]->SetBranchAddress("vtxxErr", &vtxxErr, &b_vtxxErr);
      fChain[fn]->SetBranchAddress("vtxyErr", &vtxyErr, &b_vtxyErr);
      fChain[fn]->SetBranchAddress("vtxzErr", &vtxzErr, &b_vtxzErr);
      fChain[fn]->SetBranchAddress("vtxisValid", &vtxisValid, &b_vtxisValid);
      fChain[fn]->SetBranchAddress("vtxisFake", &vtxisFake, &b_vtxisFake);
      fChain[fn]->SetBranchAddress("vtxchi2", &vtxchi2, &b_vtxchi2);
      fChain[fn]->SetBranchAddress("vtxndof", &vtxndof, &b_vtxndof);
      fChain[fn]->SetBranchAddress("vtxnTracks", &vtxnTracks, &b_vtxnTracks);
      fChain[fn]->SetBranchAddress("simvtxx", &simvtxx, &b_simvtxx);
      fChain[fn]->SetBranchAddress("simvtxy", &simvtxy, &b_simvtxy);
      fChain[fn]->SetBranchAddress("simvtxz", &simvtxz, &b_simvtxz);
	    
      //Triger
      if (filetype=="DATA"){
	fChain[fn]->SetBranchAddress("trgl1L1GTAlgo", &trgl1L1GTAlgo, &b_trgl1L1GTAlgo);
	fChain[fn]->SetBranchAddress("trgl1L1GTTech", &trgl1L1GTTech, &b_trgl1L1GTTech);
	fChain[fn]->SetBranchAddress("trgZeroBias", &trgZeroBias, &b_trgZeroBias);
      }
	    
      // // PF Candidate
      std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * PFCandidatesp4_ = 0;
      fChain[fn]->SetBranchAddress("PFCandidatesparticleId", &PFCandidatesparticleId, &b_PFCandidatesparticleId);
      fChain[fn]->SetBranchAddress("PFCandidatesp4", &PFCandidatesp4_);
      fChain[fn]->SetBranchAddress("PFCandidatesrawEcalEnergy", &PFCandidatesrawEcalEnergy, &b_PFCandidatesrawEcalEnergy);
      fChain[fn]->SetBranchAddress("PFCandidatesrawHcalEnergy", &PFCandidatesrawHcalEnergy, &b_PFCandidatesrawHcalEnergy);
      //Calo Tower
      std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * CaloTowersp4_ = 0;
      fChain[fn]->SetBranchAddress("CaloTowersp4", &CaloTowersp4_);
      fChain[fn]->SetBranchAddress("CaloTowersemEnergy", &CaloTowersemEnergy, &b_CaloTowersemEnergy);
      fChain[fn]->SetBranchAddress("CaloTowershadEnergy", &CaloTowershadEnergy, &b_CaloTowershadEnergy);
      fChain[fn]->SetBranchAddress("CaloTowershasEB", &CaloTowershasEB, &b_CaloTowershasEB);
      fChain[fn]->SetBranchAddress("CaloTowershasEE", &CaloTowershasEE, &b_CaloTowershasEE);
      fChain[fn]->SetBranchAddress("CaloTowershasHB", &CaloTowershasHB, &b_CaloTowershasHB);
      fChain[fn]->SetBranchAddress("CaloTowershasHE", &CaloTowershasHE, &b_CaloTowershasHE);
      fChain[fn]->SetBranchAddress("CaloTowershasHF", &CaloTowershasHF, &b_CaloTowershasHF);
      // Rec Hit
      fChain[fn]->SetBranchAddress("EcalRecHitenergy", &EcalRecHitenergy, &b_EcalRecHitenergy);
      fChain[fn]->SetBranchAddress("EcalRecHitEt", &EcalRecHitEt, &b_EcalRecHitEt);
      fChain[fn]->SetBranchAddress("EcalRecHittime", &EcalRecHittime, &b_EcalRecHittime);
      fChain[fn]->SetBranchAddress("EcalRecHitieta", &EcalRecHitieta, &b_EcalRecHitieta);
      fChain[fn]->SetBranchAddress("EcalRecHitiphi", &EcalRecHitiphi, &b_EcalRecHitiphi);
      fChain[fn]->SetBranchAddress("EcalRecHiteta", &EcalRecHiteta, &b_EcalRecHiteta);
      fChain[fn]->SetBranchAddress("EcalRecHitphi", &EcalRecHitphi, &b_EcalRecHitphi);
	    
      fChain[fn]->SetBranchAddress("HBHERecHitenergy", &HBHERecHitenergy, &b_HBHERecHitenergy);
      fChain[fn]->SetBranchAddress("HBHERecHitEt", &HBHERecHitEt, &b_HBHERecHitEt);
      fChain[fn]->SetBranchAddress("HBHERecHittime", &HBHERecHittime, &b_HBHERecHittime);
      fChain[fn]->SetBranchAddress("HBHERecHitieta", &HBHERecHitieta, &b_HBHERecHitieta);
      fChain[fn]->SetBranchAddress("HBHERecHitiphi", &HBHERecHitiphi, &b_HBHERecHitiphi);
      fChain[fn]->SetBranchAddress("HBHERecHitdepth", &HBHERecHitdepth, &b_HBHERecHitdepth);
      //fChain[fn]->SetBranchAddress("HBHERecHitHBHENumRecHits", &HBHERecHitHBHENumRecHits, &b_HBHERecHitHBHENumRecHits);
      fChain[fn]->SetBranchAddress("HBHERecHiteta", &HBHERecHiteta, &b_HBHERecHiteta);
      fChain[fn]->SetBranchAddress("HBHERecHitphi", &HBHERecHitphi, &b_HBHERecHitphi);
      fChain[fn]->SetBranchAddress("HFRecHitenergy", &HFRecHitenergy, &b_HFRecHitenergy);
      fChain[fn]->SetBranchAddress("HFRecHitEt", &HFRecHitEt, &b_HFRecHitEt);
      fChain[fn]->SetBranchAddress("HFRecHittime", &HFRecHittime, &b_HFRecHittime);
      fChain[fn]->SetBranchAddress("HFRecHitieta", &HFRecHitieta, &b_HFRecHitieta);
      fChain[fn]->SetBranchAddress("HFRecHitiphi", &HFRecHitiphi, &b_HFRecHitiphi);
      fChain[fn]->SetBranchAddress("HFRecHitdepth", &HFRecHitdepth, &b_HFRecHitdepth);
      //fChain[fn]->SetBranchAddress("HFRecHitHFNumRecHits", &HFRecHitHFNumRecHits, &b_HFRecHitHFNumRecHits);
      fChain[fn]->SetBranchAddress("HFRecHiteta", &HFRecHiteta, &b_HFRecHiteta);
      fChain[fn]->SetBranchAddress("HFRecHitphi", &HFRecHitphi, &b_HFRecHitphi);
	    
	    
      fChain[fn]->SetBranchAddress("CastorRecHitEnergy", &CastorRecHitEnergy, &b_CastorRecHitEnergy);
      fChain[fn]->SetBranchAddress("CastorRecHitSector", &CastorRecHitSector, &b_CastorRecHitSector);
      fChain[fn]->SetBranchAddress("CastorRecHitModule", &CastorRecHitModule, &b_CastorRecHitModule);
      fChain[fn]->SetBranchAddress("CastorRecHitisBad", &CastorRecHitisBad, &b_CastorRecHitisBad);
      fChain[fn]->SetBranchAddress("CastorRecHitisSaturated", &CastorRecHitisSaturated, &b_CastorRecHitisSaturated);
      fChain[fn]->SetBranchAddress("CastorRecHitisDesaturated", &CastorRecHitisDesaturated, &b_CastorRecHitisDesaturated);
	    
      std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * CastorTowerp4_ = 0;
      fChain[fn]->SetBranchAddress("CastorTowerp4", &CastorTowerp4_);
      fChain[fn]->SetBranchAddress("CastorToweremEnergy", &CastorToweremEnergy, &b_CastorToweremEnergy);
      fChain[fn]->SetBranchAddress("CastorTowerhadEnergy", &CastorTowerhadEnergy, &b_CastorTowerhadEnergy);
      fChain[fn]->SetBranchAddress("CastorTowerNrechits", &CastorTowerNrechits, &b_CastorTowerNrechits);
	    
      //PF Clusters
      fChain[fn]->SetBranchAddress("hcalPFClustersenergy", &hcalPFClustersenergy, &b_hcalPFClustersenergy);
      fChain[fn]->SetBranchAddress("hcalPFClusterscorrectedEnergy", &hcalPFClusterscorrectedEnergy, &b_hcalPFClusterscorrectedEnergy);
      fChain[fn]->SetBranchAddress("hcalPFClusterscorrectedEnergyUncertainty", &hcalPFClusterscorrectedEnergyUncertainty, &b_hcalPFClusterscorrectedEnergyUncertainty);
      fChain[fn]->SetBranchAddress("hcalPFClusterstime", &hcalPFClusterstime, &b_hcalPFClusterstime);
      fChain[fn]->SetBranchAddress("hcalPFClustersdepth", &hcalPFClustersdepth, &b_hcalPFClustersdepth);
      fChain[fn]->SetBranchAddress("hcalPFClusterspt", &hcalPFClusterspt, &b_hcalPFClusterspt);
      fChain[fn]->SetBranchAddress("hcalPFClustersEt", &hcalPFClustersEt, &b_hcalPFClustersEt);
      fChain[fn]->SetBranchAddress("hcalPFClusterseta", &hcalPFClusterseta, &b_hcalPFClusterseta);
      fChain[fn]->SetBranchAddress("hcalPFClustersphi", &hcalPFClustersphi, &b_hcalPFClustersphi);
      fChain[fn]->SetBranchAddress("hcalPFClusterssize", &hcalPFClusterssize, &b_hcalPFClusterssize);
      fChain[fn]->SetBranchAddress("hcalPFClustersisInClean", &hcalPFClustersisInClean, &b_hcalPFClustersisInClean);
      fChain[fn]->SetBranchAddress("hcalPFClustersisInUnClean", &hcalPFClustersisInUnClean, &b_hcalPFClustersisInUnClean);
      fChain[fn]->SetBranchAddress("hfPFClustersenergy", &hfPFClustersenergy, &b_hfPFClustersenergy);
      fChain[fn]->SetBranchAddress("hfPFClusterscorrectedEnergy", &hfPFClusterscorrectedEnergy, &b_hfPFClusterscorrectedEnergy);
      fChain[fn]->SetBranchAddress("hfPFClusterscorrectedEnergyUncertainty", &hfPFClusterscorrectedEnergyUncertainty, &b_hfPFClusterscorrectedEnergyUncertainty);
      fChain[fn]->SetBranchAddress("hfPFClusterstime", &hfPFClusterstime, &b_hfPFClusterstime);
      fChain[fn]->SetBranchAddress("hfPFClustersdepth", &hfPFClustersdepth, &b_hfPFClustersdepth);
      fChain[fn]->SetBranchAddress("hfPFClusterspt", &hfPFClusterspt, &b_hfPFClusterspt);
      fChain[fn]->SetBranchAddress("hfPFClustersEt", &hfPFClustersEt, &b_hfPFClustersEt);
      fChain[fn]->SetBranchAddress("hfPFClusterseta", &hfPFClusterseta, &b_hfPFClusterseta);
      fChain[fn]->SetBranchAddress("hfPFClustersphi", &hfPFClustersphi, &b_hfPFClustersphi);
      fChain[fn]->SetBranchAddress("hfPFClusterssize", &hfPFClusterssize, &b_hfPFClusterssize);
      fChain[fn]->SetBranchAddress("hfPFClustersisInClean", &hfPFClustersisInClean, &b_hfPFClustersisInClean);
      fChain[fn]->SetBranchAddress("hfPFClustersisInUnClean", &hfPFClustersisInUnClean, &b_hfPFClustersisInUnClean);
      fChain[fn]->SetBranchAddress("ecalPFClustersenergy", &ecalPFClustersenergy, &b_ecalPFClustersenergy);
      fChain[fn]->SetBranchAddress("ecalPFClusterscorrectedEnergy", &ecalPFClusterscorrectedEnergy, &b_ecalPFClusterscorrectedEnergy);
      fChain[fn]->SetBranchAddress("ecalPFClusterscorrectedEnergyUncertainty", &ecalPFClusterscorrectedEnergyUncertainty, &b_ecalPFClusterscorrectedEnergyUncertainty);
      fChain[fn]->SetBranchAddress("ecalPFClusterstime", &ecalPFClusterstime, &b_ecalPFClusterstime);
      fChain[fn]->SetBranchAddress("ecalPFClustersdepth", &ecalPFClustersdepth, &b_ecalPFClustersdepth);
      fChain[fn]->SetBranchAddress("ecalPFClusterspt", &ecalPFClusterspt, &b_ecalPFClusterspt);
      fChain[fn]->SetBranchAddress("ecalPFClustersEt", &ecalPFClustersEt, &b_ecalPFClustersEt);
      fChain[fn]->SetBranchAddress("ecalPFClusterseta", &ecalPFClusterseta, &b_ecalPFClusterseta);
      fChain[fn]->SetBranchAddress("ecalPFClustersphi", &ecalPFClustersphi, &b_ecalPFClustersphi);
      fChain[fn]->SetBranchAddress("ecalPFClusterssize", &ecalPFClusterssize, &b_ecalPFClusterssize);
      fChain[fn]->SetBranchAddress("ecalPFClustersisInClean", &ecalPFClustersisInClean, &b_ecalPFClustersisInClean);
      fChain[fn]->SetBranchAddress("ecalPFClustersisInUnClean", &ecalPFClustersisInUnClean, &b_ecalPFClustersisInUnClean);
      fChain[fn]->SetBranchAddress("bx", &bx, &b_bx);
	    
      // ----------------------- Cut-------------------------//
      lumimin =97;
      lumimax =311;
      emin = 5.;
      NoiseCut = 4.;
      Etabnd = 5.205;//Max Eta for CMS
      cmseta = 6.6;//Max Eta for CMS
      etamin =3.152;
      //etamax =4.889;//event select
      etamax =5.205;//event select
      etamaxMinus =-3.152;
      etaminMinus =-5.205;//event select
      minXiSD=1e-6;
	    
	    
      // event 
      Long64_t nentries = fChain[fn]->GetEntriesFast();
      cout<<"Entries "<<nentries<<endl;
      Long64_t nbytes = 0, nb = 0;
      int maxevent=10000;
      for (Long64_t ev=0; ev<nentries;ev++) {
		
	//for (Long64_t ev=0; ev<maxevent;ev++) {
		
	Long64_t iev = fChain[fn]->LoadTree(ev);
	if (iev < 0)break;
	nb = fChain[fn]->GetEntry(ev);   nbytes += nb;
		
	double progress = 10.0*ev/(1.0*nentries);
	int k = TMath::FloorNint(progress); 
	if (k > decade) 
	  cout<<10*k<<" %"<<endl;
	decade = k; 
	RecHit.clear(); 
	RecHitHCAL.clear(); 
	RecHitHF.clear();
	RecHitECAL.clear(); 
	CaloTower.clear();
	SDHFSignalTower.clear();//New Part
	SDHFVetoTower.clear();//New Part
	HCALTower.clear();
	hcalPFClustersCorrEnergy.clear(); 
	ecalPFClustersCorrEnergy.clear();
	HFPFClustersCorrEnergy.clear();
	hcalPFClustersRawEnergy.clear();
	ecalPFClustersRawEnergy.clear();
	HFPFClustersRawEnergy.clear();
	PFClusters.clear();
	GenDetEventSelect.clear();
	CastorTower.clear();
	RecHitCastor.clear();
	PFCandidate.clear();
                
		
	for (int i =0; i<nEtaBins;i++) {
	  RecHitHCALEtaSums[i]=0.;
		    
	  RecHitECALEtaSums[i]=0.;
	  RecHitHFEtaSums[i]=0.;
	  HCALTowerEtaSums[i]=0.;
	  SDHFSignalTowerEtaSums[i]=0.;
	  SDHFVetoTowerEtaSums[i]=0.;
	  CaloEtaSums[i]=0.;
	  PFCandEtaSums[i]=0.;
		    
	  PFClustersEtaSums[i]=0.;
	  PFClustersECALEtaSums[i]=0.;
	  PFClustersHCALEtaSums[i]=0.;
	  PFClustersHFEtaSums[i]=0.;
		    
	  PFClustersEtaSumsUp[i]=0.;
	  PFClustersECALEtaSumsUp[i]=0.;
	  PFClustersHCALEtaSumsUp[i]=0.;
	  PFClustersHFEtaSumsUp[i]=0.;
		    
	  PFClustersEtaSumsLo[i]=0.;
	  PFClustersECALEtaSumsLo[i]=0.;
	  PFClustersHCALEtaSumsLo[i]=0.;
	  PFClustersHFEtaSumsLo[i]=0.;
		    
	  PFClustersEtaSumsRaw[i]=0.;
	  PFClustersECALEtaSumsRaw[i]=0.;
	  PFClustersHCALEtaSumsRaw[i]=0.;
	  PFClustersHFEtaSumsRaw[i]=0.;
		    
	  GenEtaSumsDetEvntSelct[i]=0.;
	  CastorTowerEtaSums[i]=0.;
	  RecHitCastorEtaSums[i]=0.;
		    
	}
		
	// Ini. for each event
	EnergyCutRecHit=false;
	EnergyCutRecHitMinus=false;
	EnergyCutTowerMinus=false;
	EnergyCutTowerPlus=false;
	EnergyCutTower=false;
	EnergyCutRecHitPlus=false;
	EnergyCutPFCluster=false;
	EnergyCutRecHitHFAnd=false;
	RunCut=false;
	LumiCut=false;
	bxCut=false;
			    
	if (filetype =="DATA" && run==247324) RunCut=true;
	if(filetype =="MC") RunCut =true;// for MC
		
	// ----------------------- fat bunch ------------------//
	if (filetype =="DATA" && bx==208) bxCut=true;
	if(filetype =="MC") bxCut =true;// for MC
		
	// ----------------------- lumi cut ------------------//
		
	if (filetype =="DATA")LumiCut=(lumi>=lumimin &&lumi<lumimax);
	else LumiCut=true;// for MC
		
	//if(LumiCut && RunCut ){
	if(RunCut && LumiCut ){
		    
	  // ----------------------- triger cut --------------//
	  if (filetype =="DATA")TrigerPass =  (trgZeroBias== 1);
	  else TrigerPass=true;
		    
	  if(TrigerPass){
	    //-- Event Selection for Det Level --//
                
	    //------------ HF_AND ------------//
	    //----------HF Minus-------//
	    for (unsigned long cal=0; cal<CaloTowersp4_->size(); cal++){
                    
	      XYZTVector caltwr = (*CaloTowersp4_)[cal];
                    
	      if((caltwr.Eta()>=etaminMinus && caltwr.Eta()<=etamaxMinus) && ((caltwr.E())*Norm) > emin) {
                        
		EnergyCutTowerMinus=true;
	      }
	    }
                
                
	    //----------HF Plus-------//
	    for (unsigned long cal=0; cal<CaloTowersp4_->size(); cal++){
                    
	      XYZTVector caltwr = (*CaloTowersp4_)[cal];
                    
	      if((caltwr.Eta()>=etamin && caltwr.Eta()<=etamax) && ((caltwr.E())*Norm) > emin) {
                        
		EnergyCutTowerPlus=true;
	      }
	    }
                
                
                
	    if ((EnergyCutTowerMinus && !EnergyCutTowerPlus) || (!EnergyCutTowerMinus && EnergyCutTowerPlus)){
	      // Gen Level Event selection for Detlevel
	      if (filetype =="MC"){
		for (unsigned long gd=0; gd<genParticlesp4_->size(); gd++){
		  XYZTVector genDet = (*genParticlesp4_)[gd];
				    
		  if((abs(genDet.Eta())<= cmseta)  ) {
		    selcetetabin=getBin(genDet.Eta(),EtaBins, nEtaBins);
		    GenEtaSumsDetEvntSelct[selcetetabin] = GenEtaSumsDetEvntSelct[selcetetabin] + genDet.E();
		  }
		}//Gen
	      }
	      // ----------------------- ECALRecHit --------------- //
	      for(unsigned long j=0; j<EcalRecHitenergy->size(); j++) {
		selcetetabin=getBin(EcalRecHiteta->at(j),EtaBins,nEtaBins);
		RecHitECALEtaSums[selcetetabin]= RecHitECALEtaSums[selcetetabin] + EcalRecHitenergy->at(j);
	      }  
			    
	      // ----------------------- HCALRecHit --------------- //
	      for(unsigned long j=0; j<HBHERecHitenergy->size(); j++) {
		selcetetabin=getBin(HBHERecHiteta->at(j),EtaBins,nEtaBins);
		RecHitHCALEtaSums[selcetetabin]= RecHitHCALEtaSums[selcetetabin] + HBHERecHitenergy->at(j);
	      }
			    
	      // ----------------------- HFRecHit --------------- //
	      for(unsigned long j=0; j<HFRecHitenergy->size(); j++) {
		if((abs(HFRecHiteta->at(j))>=etamin && abs(HFRecHiteta->at(j))<=Etabnd)) {
		  selcetetabin=getBin(HFRecHiteta->at(j),EtaBins,nEtaBins);
		  RecHitHFEtaSums[selcetetabin]= RecHitHFEtaSums[selcetetabin] + ((HFRecHitenergy->at(j))*Norm);
		}
	      }
	     
	      
			    
	      //----------------------- CaloTower  -------------// All //New Part
	      for (unsigned long cal=0; cal<CaloTowersp4_->size(); cal++){
			      
		XYZTVector caltwr = (*CaloTowersp4_)[cal];
		selcetetabin=getBin(caltwr.Eta(),EtaBins,nEtaBins);
			      
		if(abs(caltwr.Eta()) >=etamin && abs(caltwr.Eta()) <=Etabnd) {
		  if(caltwr.E()*Norm > NoiseCut) {
		    
		    if(EnergyCutTowerMinus && !EnergyCutTowerPlus ){
		      if (caltwr.Eta() < 0 ) SDHFSignalTowerEtaSums[selcetetabin]= SDHFSignalTowerEtaSums[selcetetabin] + (caltwr.E())*Norm;//HF MC Norm
              if (caltwr.Eta() > 0 ) SDHFVetoTowerEtaSums[selcetetabin]= SDHFVetoTowerEtaSums[selcetetabin] + (caltwr.E())*Norm;//HF MC Norm
                
		    }
		    
		    if(!EnergyCutTowerMinus && EnergyCutTowerPlus ){
              if (caltwr.Eta() > 0 ) SDHFSignalTowerEtaSums[selcetetabin]= SDHFSignalTowerEtaSums[selcetetabin] + (caltwr.E())*Norm;//HF MC Norm
		      if (caltwr.Eta() < 0 ) SDHFVetoTowerEtaSums[selcetetabin]= SDHFVetoTowerEtaSums[selcetetabin] + (caltwr.E())*Norm;//HF MC Norm
		    }
		    
		    HCALTowerEtaSums[selcetetabin]= HCALTowerEtaSums[selcetetabin] + (caltwr.E())*Norm;//HF MC Norm
		    //cout << " energy "<<caltwr.E()<<endl;
		  }//HF
		}
		// out HF eta
		else {
		  HCALTowerEtaSums[selcetetabin]= HCALTowerEtaSums[selcetetabin] + (caltwr.E());
		}
			      
	      }
			    
	      // // -----------------------  PF cand  -----------------------//
	      // //PFCand
	      for (unsigned long pf=0; pf<PFCandidatesp4_->size(); pf++){
		XYZTVector pfcand = (*PFCandidatesp4_)[pf];
		//cout << " pf energy "<<pfcand.E()<< " pf eta "<< pfcand.Eta()<<endl;
			    
		// if(pfcand.E() > 10.) {
		//cout <<"event "<< ev <<" PFCandidates "<<PFCandidatesp4_->size()<<endl;
		selcetetabin=getBin(pfcand.Eta(),EtaBins, nEtaBins);
		if(abs(pfcand.Eta()) >=etamin && abs(pfcand.Eta()) <=Etabnd)PFCandEtaSums[selcetetabin]= PFCandEtaSums[selcetetabin] + pfcand.E()*Norm;
		else PFCandEtaSums[selcetetabin]= PFCandEtaSums[selcetetabin] + pfcand.E();
		//cout<<" eta "<<pfcand.Eta()<<" bin "<<selcetetabin<<" energy " << pfcand.E() <<" total PF energy "<<PFCandEtaSums[selcetetabin]<<endl;
		// }
	      }//PFCand
			    
	      //----------------------- PF Cluster --------------- //
	      //HCALcorrected energy
	      for(unsigned long pfc=0; pfc<hcalPFClusterscorrectedEnergy->size(); pfc++) {
		selcetetabin=getBin(hcalPFClusterseta->at(pfc),EtaBins, nEtaBins);
		PFClustersHCALEtaSums[selcetetabin]= PFClustersHCALEtaSums[selcetetabin]+hcalPFClusterscorrectedEnergy->at(pfc);
	      }
	      //Ecal corrected energy
	      for(unsigned long pfc=0; pfc<ecalPFClusterscorrectedEnergy->size(); pfc++) {
		selcetetabin=getBin(ecalPFClusterseta->at(pfc),EtaBins, nEtaBins);
		PFClustersECALEtaSums[selcetetabin]= PFClustersECALEtaSums[selcetetabin]+ ecalPFClusterscorrectedEnergy->at(pfc);
	      }
	      //Hf corrected energy	   
	      for(unsigned long pfc=0; pfc<hfPFClusterscorrectedEnergy->size(); pfc++) {
		if((abs(hfPFClusterseta->at(pfc))>=etamin && abs(hfPFClusterseta->at(pfc))<=Etabnd)) {
		  selcetetabin=getBin(hfPFClusterseta->at(pfc),EtaBins, nEtaBins);
		  PFClustersHFEtaSums[selcetetabin]= PFClustersHFEtaSums[selcetetabin]+((hfPFClusterscorrectedEnergy->at(pfc))*Norm);
		}
	      }
			    
	      //HCAL raw energy
	      for(unsigned long pfc=0; pfc<hcalPFClustersenergy->size(); pfc++) {
		selcetetabin=getBin(hcalPFClusterseta->at(pfc),EtaBins, nEtaBins);
		PFClustersHCALEtaSumsRaw[selcetetabin]= PFClustersHCALEtaSumsRaw[selcetetabin]+hcalPFClustersenergy->at(pfc);
				
	      }
	      //ECAL raw energy
	      for(unsigned long pfc=0; pfc< ecalPFClustersenergy->size(); pfc++) {
		selcetetabin=getBin(ecalPFClusterseta->at(pfc),EtaBins, nEtaBins);
		PFClustersECALEtaSumsRaw[selcetetabin]= PFClustersECALEtaSumsRaw[selcetetabin]+ecalPFClustersenergy->at(pfc);
	      }
	      //HF raw energy
	      for(unsigned long pfc=0; pfc<hfPFClustersenergy->size(); pfc++) {
				
		if((abs(hfPFClusterseta->at(pfc))>=etamin && abs(hfPFClusterseta->at(pfc))<=Etabnd)) { 
		  selcetetabin=getBin(hfPFClusterseta->at(pfc),EtaBins, nEtaBins);
		  PFClustersHFEtaSumsRaw[selcetetabin]= PFClustersHFEtaSumsRaw[selcetetabin]+((hfPFClustersenergy->at(pfc))*Norm);
		}
	      }
	      // --------------------Castor Tower-----------------//
	      for (unsigned long cas=0; cas<CastorTowerp4_->size(); cas++){
				
		XYZTVector castwr = (*CastorTowerp4_)[cas];
		selcetetabin=getBin(castwr.Eta(),EtaBins,nEtaBins);
		CastorTowerEtaSums[selcetetabin]= CastorTowerEtaSums[selcetetabin] + castwr.E();
	      }
                
	      // ----------------------- Castor RecHit --------------- //                                                                                                               
	      for(unsigned long j=0; j<CastorRecHitEnergy->size(); j++) {
		//selcetetabin=getBin(HFRecHiteta->at(j),EtaBins,nEtaBins);
		RecHitCastorEtaSums[0]= RecHitCastorEtaSums[0] + (CastorRecHitEnergy->at(j));
                               
	      }
                
			    
	      // Filling tree
	      float totenergycalotower,totenergySDHFSignalcalotower,totenergySDHFVetocalotower,totenergyrechit,totenergypfclusters,totenergypfcandidate;
	      for (int k=0;k<nEtaBins;k++){
		// (HFPFClustersRawEnergy[k]).push_back(PFClustersHFEtaSumsRaw[k]);
		// (Gen_DetEvntSelct[k]).push_back(GenEtaSumsDetEvntSelct[k]);
		totenergyrechit =0.;
		totenergypfclusters=0.;
		totenergycalotower=0.;
		totenergypfcandidate=0.;
		totenergySDHFSignalcalotower=0.;
		totenergySDHFVetocalotower=0.;
		
		RecHitHCAL.push_back(RecHitHCALEtaSums[k]);
		RecHitHF.push_back(RecHitHFEtaSums[k]);
		RecHitECAL.push_back(RecHitECALEtaSums[k]);
		RecHitCastor.push_back(RecHitCastorEtaSums[0]);
		if (k==0)totenergyrechit = RecHitHCALEtaSums[k]+RecHitECALEtaSums[k]+RecHitHFEtaSums[k]+RecHitCastorEtaSums[0];
		else totenergyrechit = RecHitHCALEtaSums[k]+RecHitECALEtaSums[k]+RecHitHFEtaSums[k];
		RecHit.push_back(totenergyrechit);

		HCALTower.push_back(HCALTowerEtaSums[k]);
		CastorTower.push_back(CastorTowerEtaSums[k]);
		totenergycalotower = HCALTowerEtaSums[k]+CastorTowerEtaSums[k];
		CaloTower.push_back(totenergycalotower);

		totenergySDHFSignalcalotower= SDHFSignalTowerEtaSums[k]+CastorTowerEtaSums[k];
		SDHFSignalTower.push_back(totenergySDHFSignalcalotower);
		
		totenergySDHFVetocalotower=SDHFVetoTowerEtaSums[k]+CastorTowerEtaSums[k];
		SDHFVetoTower.push_back(totenergySDHFVetocalotower);
		
		hcalPFClustersCorrEnergy.push_back(PFClustersHCALEtaSums[k]); 
		ecalPFClustersCorrEnergy.push_back(PFClustersECALEtaSums[k]);
		HFPFClustersCorrEnergy.push_back(PFClustersHFEtaSums[k]);
		hcalPFClustersRawEnergy.push_back(PFClustersHCALEtaSumsRaw[k]);
		ecalPFClustersRawEnergy.push_back(PFClustersECALEtaSumsRaw[k]);
		HFPFClustersRawEnergy.push_back(PFClustersHFEtaSumsRaw[k]);
		//totenergypfclusters = PFClustersECALEtaSums[k]+PFClustersHCALEtaSumsRaw[k]+PFClustersHFEtaSumsRaw[k]+CastorTowerEtaSums[k];
		totenergypfclusters = PFClustersECALEtaSums[k]+PFClustersHCALEtaSumsRaw[k]+PFClustersHFEtaSumsRaw[k];
		PFClusters.push_back(totenergypfclusters);

		GenDetEventSelect.push_back(GenEtaSumsDetEvntSelct[k]);

		PFCandidate.push_back(PFCandEtaSums[k]);
	      }
			    
	      TotNofEvent[f]++;
	      EnergyFlow_Det[f]->Fill(); 
	    }//HF OR Energy Cut
	  }//Trigerpass
	}//Lumi && Run && bnx Cut	
      }//Event
      cout <<"  Total event : "<<TotNofEvent[f]<<endl;
    }//file number
    fOutFile[f]->Write();
    delete fOutFile[f];
    cout<<"Filling tree and write in root file with "<<TotNofEvent[f]<<" events"<<" for file : "<<readfilesname.c_str()<<endl;
  }//File
}
//void  EnergyFlow_DetLevel_TreeProducer(int FileNumber=0)
void  EnergyFlow_GenLevel_TreeProducer_TuneCUETP8M1_3p8Tesla()

{
    gROOT->ProcessLine("#include <vector>"); 
    //gROOT->ProcessLine(".L MC.C+");
    //setTDRStyle();
    
    gDirectory->DeleteAll();
    gROOT->ForceStyle();
    gStyle->SetOptFit(0);
    gStyle->SetOptStat(0); 
    
    cout<<"file dir :   "<<readfilesdir.c_str()<<"     file number : "<<readfilesnumber_in_dir<<endl;
    static const Int_t ftyp =1;
    static const Int_t fnumber =readfilesnumber_in_dir ;

    //string fname[6]={"Data","herwigpp","pythia8_Monash","pythia8_MBR","epos","qgsjetII"};
    for (int i=0; i<ftyp;i++){
	cout << " file :"<<i<<" ==> "<<filetype.c_str()<<endl;
    };
    //gStyle->SetOptStat(111);
    bool save =true;
    string filenames ="";
    string energyname[13]={"RecHitHCAL","RecHitHF","RecHitECAL","CaloTower",
			   "hcalPFClustersCorrEnergy","ecalPFClustersCorrEnergy","HFPFClustersCorrEnergy",
			   "hcalPFClustersRawEnergy","ecalPFClustersRawEnergy","HFPFClustersRawEnergy",
			   "Gen","Events","CastorTower"};
    
    
   
    
    
    static const Int_t etyp = 13 ;
   
    char title[999];
    
    vector<float> Gen;
    vector<float> Gen_1GeV;
    vector<float> Gen_2GeV;
    vector<float> Gen_HadronElectronCut;
    vector<float> Gen_EM;
    vector<float> Gen_EM_withEnergyCuts;
    vector<float> Gen_Had;
    vector<float> Gen_Had_withEnergyCuts;
    
    TFile *fOutFile[ftyp+1];
    TTree *EnergyFlow_Gen[ftyp+1];
    
    TTree *fChain[fnumber+1];
    TFile *file[fnumber+1];
    int TotNofEventGen[ftyp+1];

    int decade = 0;

    //float Norm=1.0;
    //if (filetype=="MC") Norm=1.0/1.117;
    //else Norm=Norm;

    for (int f=0; f<ftyp; f++){
	//for (int f=FileNumber; f<FileNumber+1; f++){
	//----------------------Creating tree for output--------------//
	sprintf(title,"EFlow_GenLevel_%s_3p8Tesla.root",readfilesname.c_str());
	fOutFile[f]= new TFile(title,"RECREATE");
	//sprintf(title,"%s",fname.c_str());
	sprintf(title,"EFlow");
        EnergyFlow_Gen[f]= new TTree(title,title);
        EnergyFlow_Gen[f]->Branch("Gen",&Gen);
        EnergyFlow_Gen[f]->Branch("Gen_1GeV", &Gen_1GeV);
        EnergyFlow_Gen[f]->Branch("Gen_2GeV", &Gen_2GeV);
        EnergyFlow_Gen[f]->Branch("Gen_HadronElectronCut",&Gen_HadronElectronCut);
        EnergyFlow_Gen[f]->Branch("Gen_EM",&Gen_EM);
        EnergyFlow_Gen[f]->Branch("Gen_EM_withEnergyCuts",&Gen_EM_withEnergyCuts);
        EnergyFlow_Gen[f]->Branch("Gen_Had",&Gen_Had);
        EnergyFlow_Gen[f]->Branch("Gen_Had_withEnergyCuts",&Gen_Had_withEnergyCuts);
	TotNofEventGen[f]= 0;
	//------- File Number ---------//                                                                                                                                                
        for (int fn=0; fn < fnumber ; fn++){
            // --- open file in EOS                                                                                                                                                      
            char Fname[999];
            sprintf(Fname,"trees_%d.root",(fn+1));
            string sFname(Fname);
            string filenames=readfilesdir+sFname;
            cout<<"file : "<<filenames.c_str()<<endl;
            file[fn]   = TFile::Open(filenames.c_str(),"READ");
	    
	    // --- read tree
	    fChain[fn] = (TTree*)file[fn]->Get("EflowTree/data");
	    //Event
	    //if(filetype =="MC"){
            fChain[fn]->SetBranchAddress("run", &run, &b_run);
            fChain[fn]->SetBranchAddress("lumi", &lumi, &b_lumi);
            fChain[fn]->SetBranchAddress("event", &event, &b_event);
            fChain[fn]->SetBranchAddress("genWeight", &genWeight, &b_genWeight);
            fChain[fn]->SetBranchAddress("processID", &processID, &b_processID);
            fChain[fn]->SetBranchAddress("cmenergy", &cmenergy, &b_cmenergy);
            fChain[fn]->SetBranchAddress("puTrueNumInteractions", &puTrueNumInteractions, &b_puTrueNumInteractions);
            fChain[fn]->SetBranchAddress("PUNumInteractions", &PUNumInteractions, &b_PUNumInteractions);
            fChain[fn]->SetBranchAddress("vtxx", &vtxx, &b_vtxx);
            fChain[fn]->SetBranchAddress("vtxy", &vtxy, &b_vtxy);
            fChain[fn]->SetBranchAddress("vtxz", &vtxz, &b_vtxz);
            fChain[fn]->SetBranchAddress("vtxxErr", &vtxxErr, &b_vtxxErr);
            fChain[fn]->SetBranchAddress("vtxyErr", &vtxyErr, &b_vtxyErr);
            fChain[fn]->SetBranchAddress("vtxzErr", &vtxzErr, &b_vtxzErr);
            fChain[fn]->SetBranchAddress("vtxisValid", &vtxisValid, &b_vtxisValid);
            fChain[fn]->SetBranchAddress("vtxisFake", &vtxisFake, &b_vtxisFake);
            fChain[fn]->SetBranchAddress("vtxchi2", &vtxchi2, &b_vtxchi2);
            fChain[fn]->SetBranchAddress("vtxndof", &vtxndof, &b_vtxndof);
            fChain[fn]->SetBranchAddress("vtxnTracks", &vtxnTracks, &b_vtxnTracks);
            fChain[fn]->SetBranchAddress("simvtxx", &simvtxx, &b_simvtxx);
            fChain[fn]->SetBranchAddress("simvtxy", &simvtxy, &b_simvtxy);
            fChain[fn]->SetBranchAddress("simvtxz", &simvtxz, &b_simvtxz);
            std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * genParticlesp4_ = 0;
            
            fChain[fn]->SetBranchAddress("genParticlesp4", &genParticlesp4_);
            fChain[fn]->SetBranchAddress("genParticlescharge", &genParticlescharge, &b_genParticlescharge);
            fChain[fn]->SetBranchAddress("genParticlespdg", &genParticlespdg, &b_genParticlespdg);
            fChain[fn]->SetBranchAddress("genParticlesstatus", &genParticlesstatus, &b_genParticlesstatus);
            fChain[fn]->SetBranchAddress("Xix", &Xix, &b_Xix);
            fChain[fn]->SetBranchAddress("Xiy", &Xiy, &b_Xiy);
            fChain[fn]->SetBranchAddress("XiSD", &XiSD, &b_XiSD);
            fChain[fn]->SetBranchAddress("XiDD", &XiDD, &b_XiDD);
            
       // }
	    // ----------------------- Cut-------------------------//
	    emin = 5.;
            Etabnd = 5.205;//Max Eta for CMS
            //Etabnd = 6.6;//Max Eta for CMS
            etamin =3.152;
            etamax =5.205;//event select
            etamaxMinus =-3.152;
            etaminMinus =-5.205;//event select
            //etamax =5.205;//event select
	    minXiSD=1e-6;
	    
	    
	    // event 
	    Long64_t nentries = fChain[fn]->GetEntriesFast();
	    cout<<"Entries "<<nentries<<endl;
	    Long64_t nbytes = 0, nb = 0;
	    int maxevent=1000;
	    for (Long64_t ev=0; ev<nentries;ev++) {
		
		//for (Long64_t ev=0; ev<maxevent;ev++) {
		
		Long64_t iev = fChain[fn]->LoadTree(ev);
		if (iev < 0)break;
		nb = fChain[fn]->GetEntry(ev);   nbytes += nb;
		
		double progress = 10.0*ev/(1.0*nentries);
		int k = TMath::FloorNint(progress); 
		if (k > decade) 
		    cout<<10*k<<" %"<<endl;
		decade = k; 
            
            Gen.clear();
            Gen_1GeV.clear();
            Gen_2GeV.clear();
            Gen_HadronElectronCut.clear();
            Gen_EM.clear();
            Gen_EM_withEnergyCuts.clear();
            Gen_Had.clear();
            Gen_Had_withEnergyCuts.clear();
            
		for (int i =0; i<nEtaBins;i++) {
            
            GenEtaSums[i]=0.;
            GenEtaSums_1GeV[i]=0.;
            GenEtaSums_2GeV[i]=0.;
            GenEtaSums_HadronElectronCut[i]=0.;
            GenEtaSums_EM[i]=0.;
            GenEtaSums_EM_withEnergyCuts[i]=0.;
            GenEtaSums_Had[i]=0.;
            GenEtaSums_Had_withEnergyCuts[i]=0.;
            
		}
		
		// Ini. for each event
            XiCutGen=false;
            EnergyCutGen1GeV=false;
            EnergyCutGen2GeV=false;
        //--------------------XiCut-----------------------//
		if (filetype =="MC" && XiSD>minXiSD) XiCutGen=true;

		
        if(XiCutGen){
            
            for (unsigned long g=0; g<genParticlesp4_->size(); g++){
                XYZTVector gen = (*genParticlesp4_)[g];
                ElectronPhotonCut=false;
                EBEnergyCut=false;
                EEEnergyCut=false;
                HBEnergyCut=false;
                HEEnergyCut=false;
                HFEnergyCut=false;
                HF_EPEnergyCut=false;
                HadronCut=false;
                //Electron-Photon Cut begins
                if(genParticlespdg->at(g) ==11 || genParticlespdg->at(g) ==22) {
                    ElectronPhotonCut=true;
                    //EB
                    if((abs(gen.Eta())<= 1.479)  ) {
                        if(gen.E()> 0.23 ) {
                            EBEnergyCut=true;
                        }
                    }
                    //EE
                    if((abs(gen.Eta())>=1.479) && (abs(gen.Eta())<= 3.0 )  ) {
                        if(gen.E()> 0.6 && gen.Et()> 0.15) {
                            EEEnergyCut=true;
                        }
                    }
                    //HF
                    if((abs(gen.Eta()) >= 3.152) && (abs(gen.Eta()) <= 5.205)   ) {
                        if(gen.E()> 1.4 ) {
                            HF_EPEnergyCut=true;
                        }
                    }
                    
                } //Electron-Photon Cut ends
                //Hadron Cut begins
                if(!ElectronPhotonCut ) {
                    HadronCut=true;
                    //HB
                    if((abs(gen.Eta())<= 1.4)  ) {
                        if(gen.E()> 1. ) {
                            HBEnergyCut=true;
                        }
                    }
                    //HE
                    if((abs(gen.Eta())>=1.3) && (abs(gen.Eta())<= 3.0 ) ) {
                        if(gen.E()> 1.1 ) {
                            HEEnergyCut=true;
                        }
                    }
                    //HF
                    if((abs(gen.Eta()) >= 3.152) && (abs(gen.Eta()) <= 5.205)   ) {
                        if(gen.E()> 1.4 ) {
                            HFEnergyCut=true;
                        }
                    }
                    
                } ////Hadron Cut ends
                // -- Gen level apply only XiSD cut --//
                if((abs(gen.Eta())<= Etabnd)  ) {
                    
                    selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
                    GenEtaSums[selcetetabin]= GenEtaSums[selcetetabin] + gen.E();
                    
                    //-- Gen level apply Energy cut for each sub det both  EM and HAD particles--//
                    if (HFEnergyCut || HBEnergyCut || HEEnergyCut || EEEnergyCut || EBEnergyCut || HF_EPEnergyCut){
                        selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
                        GenEtaSums_HadronElectronCut[selcetetabin]= GenEtaSums_HadronElectronCut[selcetetabin] + gen.E();
                    }
                    
                    //--Gen level apply only EM particle cut --//
                    if (ElectronPhotonCut){
                        
                        selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
                        GenEtaSums_EM[selcetetabin]= GenEtaSums_EM[selcetetabin] + gen.E();
                        //--Gen level apply EM particle & energy cut --//
                        if (EBEnergyCut || EEEnergyCut || HF_EPEnergyCut){
                            selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
                            GenEtaSums_EM_withEnergyCuts[selcetetabin]= GenEtaSums_EM_withEnergyCuts[selcetetabin] + gen.E();
                        }
                    }
                    
                    //--Gen level apply only HAD particle cut --//
                    if (HadronCut){
                        
                        selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
                        GenEtaSums_Had[selcetetabin]= GenEtaSums_Had[selcetetabin] + gen.E();
                        //--Gen level apply HAD particle & energy cut --//
                        if (HBEnergyCut || HEEnergyCut || HFEnergyCut){
                            
                            selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
                            GenEtaSums_Had_withEnergyCuts[selcetetabin]= GenEtaSums_Had_withEnergyCuts[selcetetabin] + gen.E();
                            
                        }
                    }
                    
                    
                    //--Gen level 1 GeV cut --// 
                    if(gen.E()> 1. ) {
                        EnergyCutGen1GeV=true;
                        selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
                        
                        GenEtaSums_1GeV[selcetetabin]= GenEtaSums_1GeV[selcetetabin] + gen.E();
                        
                    }
                    
                    //--Gen level 2 GeV cut --//
                    if(gen.E()> 2. ) {
                        EnergyCutGen2GeV=true;
                        selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
                        
                        GenEtaSums_2GeV[selcetetabin]= GenEtaSums_2GeV[selcetetabin] + gen.E();
                        
                    }
                    
                    //cout<<" eta "<<gen.Eta()<<" bin "<<selcetetabin<<" energy " << gen.E() <<" total Gen energy "<<GenEtaSums[selcetetabin]<<endl;
                }// Gen particle eta cut
            }//Gen particle loop 
            TotNofEventGen[f]++;
            
            for (int k=0;k<nEtaBins;k++){
                
                Gen.push_back(GenEtaSums[k]);
                Gen_1GeV.push_back(GenEtaSums_1GeV[k]);
                Gen_2GeV.push_back(GenEtaSums_1GeV[k]);
                Gen_HadronElectronCut.push_back(GenEtaSums_HadronElectronCut[k]);
                Gen_EM.push_back(GenEtaSums_EM[k]);
                Gen_EM_withEnergyCuts.push_back(GenEtaSums_EM_withEnergyCuts[k]);
                Gen_Had.push_back(GenEtaSums_Had[k]);
                Gen_Had_withEnergyCuts.push_back(GenEtaSums_Had_withEnergyCuts[k]);
                
                
            }
            EnergyFlow_Gen[f]->Fill();
            
        }//xi cut
            
	    }//Event
	    cout <<"  Total event : "<<TotNofEventGen[f]<<endl;
	}//file number
	fOutFile[f]->Write();
	delete fOutFile[f];
	cout<<"Filling tree and write in root file with "<<TotNofEventGen[f]<<" events"<<" for file : "<<readfilesname.c_str()<<endl;
    }//File
}
void  EnergyFlow_TreeProducer()

{
    //gROOT->ProcessLine(".L tdrstyle_mod14.C");
    //setTDRStyle();
    
    gDirectory->DeleteAll();
    gROOT->ForceStyle();
    gStyle->SetOptFit(0);
    gStyle->SetOptStat(0); 
    gROOT->ProcessLine("#include <vector>"); 
    //gStyle->SetOptStat(111);
    bool save =true;
    
    string filenames[6] ={"root://eoscms.cern.ch//eos/cms/store/user/zdemirog/13TeV/Collisions15/data_ExpressPhysics_Run2015A_r247324_trees.root",
			  "root://eoscms.cern.ch//eos/cms/store/user/zdemirog/13TeV/MC/MinBias_TuneEE5C_13TeV-herwigpp_MagnetOff_trees.root",
			  "root://eoscms.cern.ch//eos/cms/store/user/zdemirog/13TeV/MC/TuneMonash_MagnetOff_TuneMonashMagnetOff.root",
			  "root://eoscms.cern.ch//eos/cms/store/user/zdemirog/13TeV/MC/MinBias_TuneMBR_13TeV-pythia8_MagnetOff_trees.root",
			  "root://eoscms.cern.ch//eos/cms/store/user/zdemirog/13TeV/MC/ReggeGribovPartonMC_13TeV-EPOS_MagnetOff_trees.root",
			  "root://eoscms.cern.ch//eos/cms/store/user/zdemirog/13TeV/MC/ReggeGribovPartonMC_13TeV-QGSJetII_MagnetOff_trees.root"
			  
			  
    };
    
    string fname[6]={"Data","herwigpp","pythia8_Monash","pythia8_MBR","epos","qgsjetII"};
    string energyname[12]={"RecHitHCAL","RecHitHF","RecHitECAL","CaloTower",
			   "hcalPFClustersCorrEnergy","ecalPFClustersCorrEnergy","HFPFClustersCorrEnergy",
			   "hcalPFClustersRawEnergy","ecalPFClustersRawEnergy","HFPFClustersRawEnergy",
			   "Gen","Events"};
    
    
   
    
    static const Int_t ftyp =6 ;// Data and MC
    static const Int_t etyp = 12 ;
   
    char title[999];
  
    vector<float> RecHitHCAL; 
    vector<float> RecHitHF;
    vector<float> RecHitECAL; 
    vector<float> CaloTower;
    vector<float> hcalPFClustersCorrEnergy; 
    vector<float> ecalPFClustersCorrEnergy;
    vector<float> HFPFClustersCorrEnergy;
    vector<float> hcalPFClustersRawEnergy;
    vector<float> ecalPFClustersRawEnergy;
    vector<float> HFPFClustersRawEnergy;
    vector<float> Gen;
    vector<float> Gen_1GeV;
    vector<float> Gen_2GeV;
    vector<float> Gen_HadronElectronCut;
    vector<float> Gen_EM;
    vector<float> Gen_EM_withEnergyCuts;
    vector<float> Gen_Had;
    vector<float> Gen_Had_withEnergyCuts;
    vector<float> Gen_DetEvntSelct;
  
    TFile *file[ftyp+1];
    TFile *fOutFile[ftyp+1];
    TTree *fChain[ftyp+1];

    TTree *EnergyFlow_Det[ftyp+1];
    TTree *EnergyFlow_Gen[ftyp+1];
    int TotNofEvent[ftyp+1];
    int TotNofEventGen[ftyp+1];


    
    for (int f=0; f<ftyp; f++){
    //for (int f=0; f<2; f++){
	//----------------------Creating tree for output--------------//
	sprintf(title,"EFlow_%s_tree_0Tesla.root",fname[f].c_str());
	fOutFile[f]= new TFile(title,"RECREATE");
	sprintf(title,"%s_Rec",fname[f].c_str());
	EnergyFlow_Det[f]= new TTree(title,title);
	EnergyFlow_Det[f]->Branch("RecHitHCAL",&RecHitHCAL); 
	EnergyFlow_Det[f]->Branch("RecHitHF",&RecHitHF);
	EnergyFlow_Det[f]->Branch("RecHitECAL",&RecHitECAL); 
	EnergyFlow_Det[f]->Branch("CaloTower",&CaloTower);
	EnergyFlow_Det[f]->Branch("hcalPFClustersCorrEnergy",&hcalPFClustersCorrEnergy); 
	EnergyFlow_Det[f]->Branch("ecalPFClustersCorrEnergy",&ecalPFClustersCorrEnergy);
	EnergyFlow_Det[f]->Branch("HFPFClustersCorrEnergy",&HFPFClustersCorrEnergy);
	EnergyFlow_Det[f]->Branch("hcalPFClustersRawEnergy",&hcalPFClustersRawEnergy);
	EnergyFlow_Det[f]->Branch("ecalPFClustersRawEnergy",&ecalPFClustersRawEnergy);
	EnergyFlow_Det[f]->Branch("HFPFClustersRawEnergy",&HFPFClustersRawEnergy);
	if (f>0){
	sprintf(title,"%s_Gen",fname[f].c_str());
	EnergyFlow_Gen[f]= new TTree(title,title);
	EnergyFlow_Gen[f]->Branch("Gen",&Gen);
	EnergyFlow_Gen[f]->Branch("Gen_1GeV", &Gen_1GeV);
	EnergyFlow_Gen[f]->Branch("Gen_2GeV", &Gen_2GeV);
	EnergyFlow_Gen[f]->Branch("Gen_HadronElectronCut",&Gen_HadronElectronCut);
	EnergyFlow_Gen[f]->Branch("Gen_EM",&Gen_EM);
	EnergyFlow_Gen[f]->Branch("Gen_EM_withEnergyCuts",&Gen_EM_withEnergyCuts);
	EnergyFlow_Gen[f]->Branch("Gen_Had",&Gen_Had);
	EnergyFlow_Gen[f]->Branch("Gen_Had_withEnergyCuts",&Gen_Had_withEnergyCuts);
	EnergyFlow_Gen[f]->Branch("Gen_DetEvntSelct",&Gen_DetEvntSelct);
	}
	// EnergyFlow[f]->Branch("GenEtaSumsDetEvntSelctHF",&GenEtaSumsDetEvntSelctHF);
	// --- open file in EOS
	file[f]   = TFile::Open(filenames[f].c_str(),"READ");
      
	cout<<"file : "<<filenames[f].c_str()<<endl;
	// --- read tree
	fChain[f] = (TTree*)file[f]->Get("EflowTree/data");
	//Event
	fChain[f]->SetBranchAddress("run", &run, &b_run);
	fChain[f]->SetBranchAddress("lumi", &lumi, &b_lumi);
	fChain[f]->SetBranchAddress("event", &event, &b_event);
	fChain[f]->SetBranchAddress("genWeight", &genWeight, &b_genWeight);
	fChain[f]->SetBranchAddress("processID", &processID, &b_processID);
	fChain[f]->SetBranchAddress("cmenergy", &cmenergy, &b_cmenergy);
	fChain[f]->SetBranchAddress("puTrueNumInteractions", &puTrueNumInteractions, &b_puTrueNumInteractions);
	fChain[f]->SetBranchAddress("PUNumInteractions", &PUNumInteractions, &b_PUNumInteractions);
      
	fChain[f]->SetBranchAddress("vtxx", &vtxx, &b_vtxx);
	fChain[f]->SetBranchAddress("vtxy", &vtxy, &b_vtxy);
	fChain[f]->SetBranchAddress("vtxz", &vtxz, &b_vtxz);
	fChain[f]->SetBranchAddress("vtxxErr", &vtxxErr, &b_vtxxErr);
	fChain[f]->SetBranchAddress("vtxyErr", &vtxyErr, &b_vtxyErr);
	fChain[f]->SetBranchAddress("vtxzErr", &vtxzErr, &b_vtxzErr);
	fChain[f]->SetBranchAddress("vtxisValid", &vtxisValid, &b_vtxisValid);
	fChain[f]->SetBranchAddress("vtxisFake", &vtxisFake, &b_vtxisFake);
	fChain[f]->SetBranchAddress("vtxchi2", &vtxchi2, &b_vtxchi2);
	fChain[f]->SetBranchAddress("vtxndof", &vtxndof, &b_vtxndof);
	fChain[f]->SetBranchAddress("vtxnTracks", &vtxnTracks, &b_vtxnTracks);
	fChain[f]->SetBranchAddress("simvtxx", &simvtxx, &b_simvtxx);
	fChain[f]->SetBranchAddress("simvtxy", &simvtxy, &b_simvtxy);
	fChain[f]->SetBranchAddress("simvtxz", &simvtxz, &b_simvtxz);
      
	//Triger
	//if (f==0){
	fChain[f]->SetBranchAddress("trgl1L1GTAlgo", &trgl1L1GTAlgo, &b_trgl1L1GTAlgo);
	fChain[f]->SetBranchAddress("trgl1L1GTTech", &trgl1L1GTTech, &b_trgl1L1GTTech);
	fChain[f]->SetBranchAddress("trgZeroBias", &trgZeroBias, &b_trgZeroBias);
	//}
      
	// // PF Candidate
	// std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * PFCandidatesp4_ = 0;
	// fChain[f]->SetBranchAddress("PFCandidatesparticleId", &PFCandidatesparticleId, &b_PFCandidatesparticleId);
	// fChain[f]->SetBranchAddress("PFCandidatesp4", &PFCandidatesp4_);
	// fChain[f]->SetBranchAddress("PFCandidatesrawEcalEnergy", &PFCandidatesrawEcalEnergy, &b_PFCandidatesrawEcalEnergy);
	// fChain[f]->SetBranchAddress("PFCandidatesrawHcalEnergy", &PFCandidatesrawHcalEnergy, &b_PFCandidatesrawHcalEnergy);
	//Calo Tower
	std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * CaloTowersp4_ = 0;
	fChain[f]->SetBranchAddress("CaloTowersp4", &CaloTowersp4_);
	fChain[f]->SetBranchAddress("CaloTowersemEnergy", &CaloTowersemEnergy, &b_CaloTowersemEnergy);
	fChain[f]->SetBranchAddress("CaloTowershadEnergy", &CaloTowershadEnergy, &b_CaloTowershadEnergy);
	fChain[f]->SetBranchAddress("CaloTowershasEB", &CaloTowershasEB, &b_CaloTowershasEB);
	fChain[f]->SetBranchAddress("CaloTowershasEE", &CaloTowershasEE, &b_CaloTowershasEE);
	fChain[f]->SetBranchAddress("CaloTowershasHB", &CaloTowershasHB, &b_CaloTowershasHB);
	fChain[f]->SetBranchAddress("CaloTowershasHE", &CaloTowershasHE, &b_CaloTowershasHE);
	fChain[f]->SetBranchAddress("CaloTowershasHF", &CaloTowershasHF, &b_CaloTowershasHF);
	//Gen
	std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * genParticlesp4_ = 0;
	if (f>0){
	    fChain[f]->SetBranchAddress("genParticlesp4", &genParticlesp4_);
	    fChain[f]->SetBranchAddress("genParticlescharge", &genParticlescharge, &b_genParticlescharge);
	    fChain[f]->SetBranchAddress("genParticlespdg", &genParticlespdg, &b_genParticlespdg);
	    fChain[f]->SetBranchAddress("genParticlesstatus", &genParticlesstatus, &b_genParticlesstatus);
	    fChain[f]->SetBranchAddress("Xix", &Xix, &b_Xix);
	    fChain[f]->SetBranchAddress("Xiy", &Xiy, &b_Xiy);
	    fChain[f]->SetBranchAddress("XiSD", &XiSD, &b_XiSD);
	    fChain[f]->SetBranchAddress("XiDD", &XiDD, &b_XiDD);
	}
	// Rec Hit
	fChain[f]->SetBranchAddress("EcalRecHitenergy", &EcalRecHitenergy, &b_EcalRecHitenergy);
	fChain[f]->SetBranchAddress("EcalRecHitEt", &EcalRecHitEt, &b_EcalRecHitEt);
	fChain[f]->SetBranchAddress("EcalRecHittime", &EcalRecHittime, &b_EcalRecHittime);
	fChain[f]->SetBranchAddress("EcalRecHitieta", &EcalRecHitieta, &b_EcalRecHitieta);
	fChain[f]->SetBranchAddress("EcalRecHitiphi", &EcalRecHitiphi, &b_EcalRecHitiphi);
	fChain[f]->SetBranchAddress("EcalRecHiteta", &EcalRecHiteta, &b_EcalRecHiteta);
	fChain[f]->SetBranchAddress("EcalRecHitphi", &EcalRecHitphi, &b_EcalRecHitphi);
      
	fChain[f]->SetBranchAddress("HBHERecHitenergy", &HBHERecHitenergy, &b_HBHERecHitenergy);
	fChain[f]->SetBranchAddress("HBHERecHitEt", &HBHERecHitEt, &b_HBHERecHitEt);
	fChain[f]->SetBranchAddress("HBHERecHittime", &HBHERecHittime, &b_HBHERecHittime);
	fChain[f]->SetBranchAddress("HBHERecHitieta", &HBHERecHitieta, &b_HBHERecHitieta);
	fChain[f]->SetBranchAddress("HBHERecHitiphi", &HBHERecHitiphi, &b_HBHERecHitiphi);
	fChain[f]->SetBranchAddress("HBHERecHitdepth", &HBHERecHitdepth, &b_HBHERecHitdepth);
	//fChain[f]->SetBranchAddress("HBHERecHitHBHENumRecHits", &HBHERecHitHBHENumRecHits, &b_HBHERecHitHBHENumRecHits);
	fChain[f]->SetBranchAddress("HBHERecHiteta", &HBHERecHiteta, &b_HBHERecHiteta);
	fChain[f]->SetBranchAddress("HBHERecHitphi", &HBHERecHitphi, &b_HBHERecHitphi);
	fChain[f]->SetBranchAddress("HFRecHitenergy", &HFRecHitenergy, &b_HFRecHitenergy);
	fChain[f]->SetBranchAddress("HFRecHitEt", &HFRecHitEt, &b_HFRecHitEt);
	fChain[f]->SetBranchAddress("HFRecHittime", &HFRecHittime, &b_HFRecHittime);
	fChain[f]->SetBranchAddress("HFRecHitieta", &HFRecHitieta, &b_HFRecHitieta);
	fChain[f]->SetBranchAddress("HFRecHitiphi", &HFRecHitiphi, &b_HFRecHitiphi);
	fChain[f]->SetBranchAddress("HFRecHitdepth", &HFRecHitdepth, &b_HFRecHitdepth);
	//fChain[f]->SetBranchAddress("HFRecHitHFNumRecHits", &HFRecHitHFNumRecHits, &b_HFRecHitHFNumRecHits);
	fChain[f]->SetBranchAddress("HFRecHiteta", &HFRecHiteta, &b_HFRecHiteta);
	fChain[f]->SetBranchAddress("HFRecHitphi", &HFRecHitphi, &b_HFRecHitphi);
      
	/*
	  fChain[f]->SetBranchAddress("CastorRecHitEnergy", &CastorRecHitEnergy, &b_CastorRecHitEnergy);
	  fChain[f]->SetBranchAddress("CastorRecHitSector", &CastorRecHitSector, &b_CastorRecHitSector);
	  fChain[f]->SetBranchAddress("CastorRecHitModule", &CastorRecHitModule, &b_CastorRecHitModule);
	  fChain[f]->SetBranchAddress("CastorRecHitisBad", &CastorRecHitisBad, &b_CastorRecHitisBad);
	  fChain[f]->SetBranchAddress("CastorRecHitisSaturated", &CastorRecHitisSaturated, &b_CastorRecHitisSaturated);
	  fChain[f]->SetBranchAddress("CastorRecHitisDesaturated", &CastorRecHitisDesaturated, &b_CastorRecHitisDesaturated);
	
	  std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * CastorTowerp4_ = 0;
	  fChain[f]->SetBranchAddress("CastorTowerp4", &CastorTowerp4_);
	  fChain[f]->SetBranchAddress("CastorToweremEnergy", &CastorToweremEnergy, &b_CastorToweremEnergy);
	  fChain[f]->SetBranchAddress("CastorTowerhadEnergy", &CastorTowerhadEnergy, &b_CastorTowerhadEnergy);
	  fChain[f]->SetBranchAddress("CastorTowerNrechits", &CastorTowerNrechits, &b_CastorTowerNrechits);
	*/
	//PF Clusters
	fChain[f]->SetBranchAddress("hcalPFClustersenergy", &hcalPFClustersenergy, &b_hcalPFClustersenergy);
	fChain[f]->SetBranchAddress("hcalPFClusterscorrectedEnergy", &hcalPFClusterscorrectedEnergy, &b_hcalPFClusterscorrectedEnergy);
	fChain[f]->SetBranchAddress("hcalPFClusterscorrectedEnergyUncertainty", &hcalPFClusterscorrectedEnergyUncertainty, &b_hcalPFClusterscorrectedEnergyUncertainty);
	fChain[f]->SetBranchAddress("hcalPFClusterstime", &hcalPFClusterstime, &b_hcalPFClusterstime);
	fChain[f]->SetBranchAddress("hcalPFClustersdepth", &hcalPFClustersdepth, &b_hcalPFClustersdepth);
	fChain[f]->SetBranchAddress("hcalPFClusterspt", &hcalPFClusterspt, &b_hcalPFClusterspt);
	fChain[f]->SetBranchAddress("hcalPFClustersEt", &hcalPFClustersEt, &b_hcalPFClustersEt);
	fChain[f]->SetBranchAddress("hcalPFClusterseta", &hcalPFClusterseta, &b_hcalPFClusterseta);
	fChain[f]->SetBranchAddress("hcalPFClustersphi", &hcalPFClustersphi, &b_hcalPFClustersphi);
	fChain[f]->SetBranchAddress("hcalPFClusterssize", &hcalPFClusterssize, &b_hcalPFClusterssize);
	fChain[f]->SetBranchAddress("hcalPFClustersisInClean", &hcalPFClustersisInClean, &b_hcalPFClustersisInClean);
	fChain[f]->SetBranchAddress("hcalPFClustersisInUnClean", &hcalPFClustersisInUnClean, &b_hcalPFClustersisInUnClean);
	fChain[f]->SetBranchAddress("hfPFClustersenergy", &hfPFClustersenergy, &b_hfPFClustersenergy);
	fChain[f]->SetBranchAddress("hfPFClusterscorrectedEnergy", &hfPFClusterscorrectedEnergy, &b_hfPFClusterscorrectedEnergy);
	fChain[f]->SetBranchAddress("hfPFClusterscorrectedEnergyUncertainty", &hfPFClusterscorrectedEnergyUncertainty, &b_hfPFClusterscorrectedEnergyUncertainty);
	fChain[f]->SetBranchAddress("hfPFClusterstime", &hfPFClusterstime, &b_hfPFClusterstime);
	fChain[f]->SetBranchAddress("hfPFClustersdepth", &hfPFClustersdepth, &b_hfPFClustersdepth);
	fChain[f]->SetBranchAddress("hfPFClusterspt", &hfPFClusterspt, &b_hfPFClusterspt);
	fChain[f]->SetBranchAddress("hfPFClustersEt", &hfPFClustersEt, &b_hfPFClustersEt);
	fChain[f]->SetBranchAddress("hfPFClusterseta", &hfPFClusterseta, &b_hfPFClusterseta);
	fChain[f]->SetBranchAddress("hfPFClustersphi", &hfPFClustersphi, &b_hfPFClustersphi);
	fChain[f]->SetBranchAddress("hfPFClusterssize", &hfPFClusterssize, &b_hfPFClusterssize);
	fChain[f]->SetBranchAddress("hfPFClustersisInClean", &hfPFClustersisInClean, &b_hfPFClustersisInClean);
	fChain[f]->SetBranchAddress("hfPFClustersisInUnClean", &hfPFClustersisInUnClean, &b_hfPFClustersisInUnClean);
	fChain[f]->SetBranchAddress("ecalPFClustersenergy", &ecalPFClustersenergy, &b_ecalPFClustersenergy);
	fChain[f]->SetBranchAddress("ecalPFClusterscorrectedEnergy", &ecalPFClusterscorrectedEnergy, &b_ecalPFClusterscorrectedEnergy);
	fChain[f]->SetBranchAddress("ecalPFClusterscorrectedEnergyUncertainty", &ecalPFClusterscorrectedEnergyUncertainty, &b_ecalPFClusterscorrectedEnergyUncertainty);
	fChain[f]->SetBranchAddress("ecalPFClusterstime", &ecalPFClusterstime, &b_ecalPFClusterstime);
	fChain[f]->SetBranchAddress("ecalPFClustersdepth", &ecalPFClustersdepth, &b_ecalPFClustersdepth);
	fChain[f]->SetBranchAddress("ecalPFClusterspt", &ecalPFClusterspt, &b_ecalPFClusterspt);
	fChain[f]->SetBranchAddress("ecalPFClustersEt", &ecalPFClustersEt, &b_ecalPFClustersEt);
	fChain[f]->SetBranchAddress("ecalPFClusterseta", &ecalPFClusterseta, &b_ecalPFClusterseta);
	fChain[f]->SetBranchAddress("ecalPFClustersphi", &ecalPFClustersphi, &b_ecalPFClustersphi);
	fChain[f]->SetBranchAddress("ecalPFClusterssize", &ecalPFClusterssize, &b_ecalPFClusterssize);
	fChain[f]->SetBranchAddress("ecalPFClustersisInClean", &ecalPFClustersisInClean, &b_ecalPFClustersisInClean);
	fChain[f]->SetBranchAddress("ecalPFClustersisInUnClean", &ecalPFClustersisInUnClean, &b_ecalPFClustersisInUnClean);
	fChain[f]->SetBranchAddress("bx", &bx, &b_bx);

      
      
	// ----------------------- Cut-------------------------//
	lumimin =88;
	lumimax =1000;
	emin = 5.;
	Etabnd = 5.191;//Max Eta for CMS
	etamin =3.139;
	etamax =4.889;//event select
	etamaxMinus =-3.139;
	etaminMinus =-4.889;//event select
	//etamax =5.191;//event select 
	minXiSD=1e-6;
	// ----------------------- Event -----------------------//
  
	Long64_t nentries = fChain[f]->GetEntriesFast();
	cout<<"Entries "<<nentries<<endl;
  
  
	Long64_t nbytes = 0, nb = 0;

	TotNofEvent[f]= 0;
	TotNofEventGen[f]=0;

	int maxevent=10000;
	for (Long64_t ev=0; ev<nentries;ev++) {
      
	//for (Long64_t ev=0; ev<maxevent;ev++) {
	
	    Long64_t iev = fChain[f]->LoadTree(ev);
	    if (iev < 0)break;
	    nb = fChain[f]->GetEntry(ev);   nbytes += nb;

	    RecHitHCAL.clear(); 
	    RecHitHF.clear();
	    RecHitECAL.clear(); 
	    CaloTower.clear();
	    hcalPFClustersCorrEnergy.clear(); 
	    ecalPFClustersCorrEnergy.clear();
	    HFPFClustersCorrEnergy.clear();
	    hcalPFClustersRawEnergy.clear();
	    ecalPFClustersRawEnergy.clear();
	    HFPFClustersRawEnergy.clear();
	    Gen.clear();
	    Gen_1GeV.clear();
	    Gen_2GeV.clear();
	    Gen_HadronElectronCut.clear();
	    Gen_EM.clear();
	    Gen_EM_withEnergyCuts.clear();
	    Gen_Had.clear();
	    Gen_Had_withEnergyCuts.clear();
	    Gen_DetEvntSelct.clear();
	    for (int i =0; i<nEtaBins;i++) {
		RecHitHCALEtaSums[i]=0.;
	   
		RecHitECALEtaSums[i]=0.;
		RecHitHFEtaSums[i]=0.;
		CaloEtaSums[i]=0.;
		//PFCandEtaSums[i]=0.;
 
		PFClustersEtaSums[i]=0.;
		PFClustersECALEtaSums[i]=0.;
		PFClustersHCALEtaSums[i]=0.;
		PFClustersHFEtaSums[i]=0.;
	
		PFClustersEtaSumsUp[i]=0.;
		PFClustersECALEtaSumsUp[i]=0.;
		PFClustersHCALEtaSumsUp[i]=0.;
		PFClustersHFEtaSumsUp[i]=0.;
	
		PFClustersEtaSumsLo[i]=0.;
		PFClustersECALEtaSumsLo[i]=0.;
		PFClustersHCALEtaSumsLo[i]=0.;
		PFClustersHFEtaSumsLo[i]=0.;
	  
		PFClustersEtaSumsRaw[i]=0.;
		PFClustersECALEtaSumsRaw[i]=0.;
		PFClustersHCALEtaSumsRaw[i]=0.;
		PFClustersHFEtaSumsRaw[i]=0.;
	 
		GenEtaSums[i]=0.;
		GenEtaSums_1GeV[i]=0.;
		GenEtaSums_2GeV[i]=0.;
		GenEtaSums_HadronElectronCut[i]=0.;
		GenEtaSums_EM[i]=0.;
		GenEtaSums_EM_withEnergyCuts[i]=0.;
		GenEtaSums_Had[i]=0.;
		GenEtaSums_Had_withEnergyCuts[i]=0.;
		GenEtaSumsDetEvntSelct[i]=0.;
	    }
      
	    // -----------------------  Gen  -----------------------//
	    //event selection for Gen Level
	    //
	    if (f>0){
		XiCutGen=false;
		EnergyCutGen1GeV=false;
		EnergyCutGen2GeV=false;

		// Aply XiSD
		if(XiSD>minXiSD)XiCutGen=true;
		//(abs(gen_.Eta())<=etamin && abs(gen_.Eta())>=etamax)
	  
		if(XiCutGen){
	      
		    for (unsigned long g=0; g<genParticlesp4_->size(); g++){
			XYZTVector gen = (*genParticlesp4_)[g];
			ElectronPhotonCut=false;
			EBEnergyCut=false;
			EEEnergyCut=false;
			HBEnergyCut=false;
			HEEnergyCut=false;
			HFEnergyCut=false;
			HF_EPEnergyCut=false;
			HadronCut=false;
			//Electron-Photon Cut begins
			if(genParticlespdg->at(g) ==11 || genParticlespdg->at(g) ==22) {
			    ElectronPhotonCut=true;
			    //EB
			    if((abs(gen.Eta())<= 1.479)  ) {
				if(gen.E()> 0.23 ) {
				    EBEnergyCut=true;
				}
			    }
			    //EE
			    if((abs(gen.Eta())>=1.479) && (abs(gen.Eta())<= 3.0 )  ) {
				if(gen.E()> 0.6 && gen.Et()> 0.15) {
				    EEEnergyCut=true;
				}
			    }
			    //HF
			    if((abs(gen.Eta()) >= 2.8) && (abs(gen.Eta()) <= 5.191)   ) {
				if(gen.E()> 1.4 ) {
				    HF_EPEnergyCut=true;
				}
			    }
		      
			} //Electron-Photon Cut ends
			//Hadron Cut begins
			if(!ElectronPhotonCut ) {
			    HadronCut=true;
			    //HB
			    if((abs(gen.Eta())<= 1.4)  ) {
				if(gen.E()> 1. ) {
				    HBEnergyCut=true;
				}
			    }
			    //HE
			    if((abs(gen.Eta())>=1.3) && (abs(gen.Eta())<= 3.0 ) ) {
				if(gen.E()> 1.1 ) {
				    HEEnergyCut=true;
				}
			    }
			    //HF
			    if((abs(gen.Eta()) >= 2.8) && (abs(gen.Eta()) <= 5.191)   ) {
				if(gen.E()> 1.4 ) {
				    HFEnergyCut=true;
				}
			    }
		      
			} ////Hadron Cut ends
			// -- Gen level apply only XiSD cut --//
			if((abs(gen.Eta())<= Etabnd)  ) {
		      
			    selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
			    GenEtaSums[selcetetabin]= GenEtaSums[selcetetabin] + gen.E();
		      		      
			    //-- Gen level apply Energy cut for each sub det both  EM and HAD particles--//
			    if (HFEnergyCut || HBEnergyCut || HEEnergyCut || EEEnergyCut || EBEnergyCut || HF_EPEnergyCut){
				selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
				GenEtaSums_HadronElectronCut[selcetetabin]= GenEtaSums_HadronElectronCut[selcetetabin] + gen.E();
			    }
		      
			    //--Gen level apply only EM particle cut --// 
			    if (ElectronPhotonCut){
			  
				selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
				GenEtaSums_EM[selcetetabin]= GenEtaSums_EM[selcetetabin] + gen.E();
				//--Gen level apply EM particle & energy cut --//
				if (EBEnergyCut || EEEnergyCut || HF_EPEnergyCut){
				    selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
				    GenEtaSums_EM_withEnergyCuts[selcetetabin]= GenEtaSums_EM_withEnergyCuts[selcetetabin] + gen.E();
				}
			    }
		      
			    //--Gen level apply only HAD particle cut --// 
			    if (HadronCut){
		  
				selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
				GenEtaSums_Had[selcetetabin]= GenEtaSums_Had[selcetetabin] + gen.E();
				//--Gen level apply HAD particle & energy cut --//
				if (HBEnergyCut || HEEnergyCut || HFEnergyCut){
			 
				    selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
				    GenEtaSums_Had_withEnergyCuts[selcetetabin]= GenEtaSums_Had_withEnergyCuts[selcetetabin] + gen.E();
			 
				}
			    }
		      
             
			    //--Gen level 1 GeV cut --// 
			    if(gen.E()> 1. ) {
				EnergyCutGen1GeV=true;
				selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
                          
				GenEtaSums_1GeV[selcetetabin]= GenEtaSums_1GeV[selcetetabin] + gen.E();
                          
			    }
                      
			    //--Gen level 2 GeV cut --//
			    if(gen.E()> 2. ) {
				EnergyCutGen2GeV=true;
				selcetetabin=getBin(gen.Eta(),EtaBins, nEtaBins);
                          
				GenEtaSums_2GeV[selcetetabin]= GenEtaSums_2GeV[selcetetabin] + gen.E();
                          
			    }
                      
			    //cout<<" eta "<<gen.Eta()<<" bin "<<selcetetabin<<" energy " << gen.E() <<" total Gen energy "<<GenEtaSums[selcetetabin]<<endl;
			}// Gen particle eta cut
		    }//Gen particle loop 
		    TotNofEventGen[f]++;
	     
		}//xi cut
	  
		for (int k=0;k<nEtaBins;k++){
		   
		    Gen.push_back(GenEtaSums[k]);
		    Gen_1GeV.push_back(GenEtaSums_1GeV[k]);
		    Gen_2GeV.push_back(GenEtaSums_1GeV[k]);
		    Gen_HadronElectronCut.push_back(GenEtaSums_HadronElectronCut[k]);
		    Gen_EM.push_back(GenEtaSums_EM[k]);
		    Gen_EM_withEnergyCuts.push_back(GenEtaSums_EM_withEnergyCuts[k]);
		    Gen_Had.push_back(GenEtaSums_Had[k]);
		    Gen_Had_withEnergyCuts.push_back(GenEtaSums_Had_withEnergyCuts[k]);
	      
	      
		}
		EnergyFlow_Gen[f]->Fill();
	    }//file cut
      
     
	    // Ini. for each event
	    EnergyCutRecHit=false;
	    EnergyCutRecHitMinus=false;
	    EnergyCutTowerMinus=false;
	    EnergyCutTowerPlus=false;
	    EnergyCutTower=false;
	    EnergyCutRecHitPlus=false;
	    EnergyCutPFCluster=false;
	    EnergyCutRecHitHFAnd=false;
	    RunCut=false;
	    LumiCut=false;
	    bxCut=false;
      
      
	    // if (f==0 && run==251721){
	    if (f==0 && run==247324) RunCut=true;
	    else RunCut =true;// for MC
            
	    // ----------------------- fat bunch ------------------//
	    if (f==0 && bx==208) bxCut=true;
	    else bxCut =true;// for MC
            
	    // ----------------------- lumi cut ------------------//
      
	    if (f==0)LumiCut=(lumi>=lumimin &&lumi<lumimax);
	    else LumiCut=true;// for MC
      
	    //if(LumiCut && RunCut ){
	    if(RunCut && LumiCut && bxCut){
	  
		// ----------------------- triger cut --------------//
		if (f==0)TrigerPass =  (trgZeroBias== 1);
		else TrigerPass=true;
	  
		if(TrigerPass){
		    //-- Event Selection for Det Level --//
		    //--------- HF OR-------//
		    for(unsigned long cal=0; cal<CaloTowersp4_->size(); cal++){
			XYZTVector caltwr = (*CaloTowersp4_)[cal];
		  
			if((abs(caltwr.Eta())>=etamin && abs(caltwr.Eta())<=etamax) && caltwr.E() > emin) {
			    EnergyCutTower=true;
			}
		    }
		    if (EnergyCutTower){
			// Gen Level Event selection for Detlevel
			if (f>0){
			    for (unsigned long gd=0; gd<genParticlesp4_->size(); gd++){
				XYZTVector genDet = (*genParticlesp4_)[gd];
			  
				if((abs(genDet.Eta())<= Etabnd)  ) {
				    selcetetabin=getBin(genDet.Eta(),EtaBins, nEtaBins);
				    GenEtaSumsDetEvntSelct[selcetetabin] = GenEtaSumsDetEvntSelct[selcetetabin] + genDet.E();
				}
			    }//Gen
			}
			// ----------------------- ECALRecHit --------------- //
			for(unsigned long j=0; j<EcalRecHitenergy->size(); j++) {
			    selcetetabin=getBin(EcalRecHiteta->at(j),EtaBins,nEtaBins);
			    RecHitECALEtaSums[selcetetabin]= RecHitECALEtaSums[selcetetabin] + EcalRecHitenergy->at(j);
			}  
		  
			// ----------------------- HCALRecHit --------------- //
			for(unsigned long j=0; j<HBHERecHitenergy->size(); j++) {
			    selcetetabin=getBin(HBHERecHiteta->at(j),EtaBins,nEtaBins);
			    RecHitHCALEtaSums[selcetetabin]= RecHitHCALEtaSums[selcetetabin] + HBHERecHitenergy->at(j);
			}
		  
			// ----------------------- HFRecHit --------------- //
			for(unsigned long j=0; j<HFRecHitenergy->size(); j++) {
			    if((abs(HFRecHiteta->at(j))>=etamin && abs(HFRecHiteta->at(j))<=Etabnd)) {
				selcetetabin=getBin(HFRecHiteta->at(j),EtaBins,nEtaBins);
				RecHitHFEtaSums[selcetetabin]= RecHitHFEtaSums[selcetetabin] + HFRecHitenergy->at(j);
			    }
			}  
			//----------------------- CaloTower  -------------//
			for (unsigned long cal=0; cal<CaloTowersp4_->size(); cal++){
		      
			    XYZTVector caltwr = (*CaloTowersp4_)[cal];
			    selcetetabin=getBin(caltwr.Eta(),EtaBins,nEtaBins);
			    CaloEtaSums[selcetetabin]= CaloEtaSums[selcetetabin] + caltwr.E();
			}
		  
			// // -----------------------  PF cand  -----------------------//
			// //PFCand
			// for (unsigned long pf=0; pf<PFCandidatesp4_->size(); pf++){
			// 	XYZTVector pfcand = (*PFCandidatesp4_)[pf];
			// 	//cout << " pf energy "<<pfcand.E()<< " pf eta "<< pfcand.Eta()<<endl;
		  
			// 	// if(pfcand.E() > 10.) {
			// 	//cout <<"event "<< ev <<" PFCandidates "<<PFCandidatesp4_->size()<<endl; 
			// 	selcetetabin=getBin(pfcand.Eta(),EtaBins, nEtaBins);
		  
			// 	PFCandEtaSums[selcetetabin]= PFCandEtaSums[selcetetabin] + pfcand.E();
		  
			// 	//cout<<" eta "<<pfcand.Eta()<<" bin "<<selcetetabin<<" energy " << pfcand.E() <<" total PF energy "<<PFCandEtaSums[selcetetabin]<<endl;
			// 	// }
			// }//PFCand
		  
			//----------------------- PF Cluster --------------- //
			//HCALcorrected energy
			for(unsigned long pfc=0; pfc<hcalPFClusterscorrectedEnergy->size(); pfc++) {
			    selcetetabin=getBin(hcalPFClusterseta->at(pfc),EtaBins, nEtaBins);
			    PFClustersHCALEtaSums[selcetetabin]= PFClustersHCALEtaSums[selcetetabin]+hcalPFClusterscorrectedEnergy->at(pfc);
			}
			//Ecal corrected energy
			for(unsigned long pfc=0; pfc<ecalPFClusterscorrectedEnergy->size(); pfc++) {
			    selcetetabin=getBin(ecalPFClusterseta->at(pfc),EtaBins, nEtaBins);
			    PFClustersECALEtaSums[selcetetabin]= PFClustersECALEtaSums[selcetetabin]+ ecalPFClusterscorrectedEnergy->at(pfc);
			}
			//Hf corrected energy	   
			for(unsigned long pfc=0; pfc<hfPFClusterscorrectedEnergy->size(); pfc++) {
			    if((abs(hfPFClusterseta->at(pfc))>=etamin && abs(hfPFClusterseta->at(pfc))<=Etabnd)) {
				selcetetabin=getBin(hfPFClusterseta->at(pfc),EtaBins, nEtaBins);
				PFClustersHFEtaSums[selcetetabin]= PFClustersHFEtaSums[selcetetabin]+hfPFClusterscorrectedEnergy->at(pfc);
			    }
			}
		  
			//HCAL raw energy
			for(unsigned long pfc=0; pfc<hcalPFClustersenergy->size(); pfc++) {
			    selcetetabin=getBin(hcalPFClusterseta->at(pfc),EtaBins, nEtaBins);
			    PFClustersHCALEtaSumsRaw[selcetetabin]= PFClustersHCALEtaSumsRaw[selcetetabin]+hcalPFClustersenergy->at(pfc);
		      
			}
			//ECAL raw energy
			for(unsigned long pfc=0; pfc< ecalPFClustersenergy->size(); pfc++) {
			    selcetetabin=getBin(ecalPFClusterseta->at(pfc),EtaBins, nEtaBins);
			    PFClustersECALEtaSumsRaw[selcetetabin]= PFClustersECALEtaSumsRaw[selcetetabin]+ecalPFClustersenergy->at(pfc);
			}
			//HF raw energy
			for(unsigned long pfc=0; pfc<hfPFClustersenergy->size(); pfc++) {
		      
			    if((abs(hfPFClusterseta->at(pfc))>=etamin && abs(hfPFClusterseta->at(pfc))<=Etabnd) ) { 
				selcetetabin=getBin(hfPFClusterseta->at(pfc),EtaBins, nEtaBins);
				PFClustersHFEtaSumsRaw[selcetetabin]= PFClustersHFEtaSumsRaw[selcetetabin]+hfPFClustersenergy->at(pfc);
			    }
			}
		  
			// Filling histogram
		  
			for (int k=0;k<nEtaBins;k++){
			   			    // (HFPFClustersRawEnergy[k]).push_back(PFClustersHFEtaSumsRaw[k]);
			    // (Gen_DetEvntSelct[k]).push_back(GenEtaSumsDetEvntSelct[k]);

			    RecHitHCAL.push_back(RecHitHCALEtaSums[k]);
			    RecHitHF.push_back(RecHitHFEtaSums[k]);
			    RecHitECAL.push_back(RecHitECALEtaSums[k]); 
			    CaloTower.push_back(CaloEtaSums[k]); 
			    hcalPFClustersCorrEnergy.push_back(PFClustersHCALEtaSums[k]); 
			    ecalPFClustersCorrEnergy.push_back(PFClustersECALEtaSums[k]);
			    HFPFClustersCorrEnergy.push_back(PFClustersHFEtaSums[k]);
			    hcalPFClustersRawEnergy.push_back(PFClustersHCALEtaSumsRaw[k]);
			    ecalPFClustersRawEnergy.push_back(PFClustersECALEtaSumsRaw[k]);
			    HFPFClustersRawEnergy.push_back(PFClustersHFEtaSumsRaw[k]);
			    Gen_DetEvntSelct.push_back(GenEtaSumsDetEvntSelct[k]);
			    
			}
		  
			TotNofEvent[f]++;
			EnergyFlow_Det[f]->Fill(); 
		    }//HF OR Energy Cut
		}//Trigerpass
	    }//Lumi && Run && bnx Cut
     

	   
	}//Event
	cout <<filenames[f].c_str()<<"  Total event : "<<TotNofEvent[f]<<endl;
	cout <<filenames[f].c_str()<<"  Total event Gen: "<<TotNofEventGen[f]<<endl;
	fOutFile[f]->Write();
	delete fOutFile[f];
    }//File
  
    
    
  
  
}
Exemplo n.º 4
0
double read() {


  TRandom R;
  TStopwatch timer;


  TH1D * h1 = new TH1D("h1","total event  energy ",100,0,1000.);
  TH1D * h2 = new TH1D("h2","Number of track per event",21,-0.5,20.5);
  TH1D * h3 = new TH1D("h3","Track Energy",100,0,200);
  TH1D * h4 = new TH1D("h4","Track Pt",100,0,100);
  TH1D * h5 = new TH1D("h5","Track Eta",100,-5,5);
  TH1D * h6 = new TH1D("h6","Track Cos(theta)",100,-1,1);


  TFile f1("mathcoreLV.root");

  // create tree
  TTree *t1 = (TTree*)f1.Get("t1");

  std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * pTracks = 0;
  t1->SetBranchAddress("tracks",&pTracks);

  timer.Start();
  int n = (int) t1->GetEntries();
  std::cout << " Tree Entries " << n << std::endl;
  double sum=0;
  for (int i = 0; i < n; ++i) {
    t1->GetEntry(i);
    int ntrk = pTracks->size();
    h3->Fill(ntrk);
    XYZTVector q;
    for (int j = 0; j < ntrk; ++j) {
      XYZTVector v = (*pTracks)[j];
      q += v;
      h3->Fill(v.E());
      h4->Fill(v.Pt());
      h5->Fill(v.Eta());
      h6->Fill(cos(v.Theta()));
      sum += v.x() + v.y() + v.z() + v.t();
    }
    h1->Fill(q.E() );
    h2->Fill(ntrk);
  }


  timer.Stop();
  std::cout << " Time for new Vector " << timer.RealTime() << "  " << timer.CpuTime() << std::endl;



  TCanvas *c1 = new TCanvas("c1","demo of Trees",10,10,600,800);
  c1->Divide(2,3);

  c1->cd(1);
  h1->Draw();
  c1->cd(2);
  h2->Draw();
  c1->cd(3);
  h3->Draw();
  c1->cd(3);
  h3->Draw();
  c1->cd(4);
  h4->Draw();
  c1->cd(5);
  h5->Draw();
  c1->cd(6);
  h6->Draw();

  return sum;
}
void  EnergyFlow_DataZeroBias_TreeProducer_withCastor(int FileNumber=0)

{
    
    //gROOT->ProcessLine(".L tdrstyle_mod14.C");
    //setTDRStyle();
    
    gDirectory->DeleteAll();
    gROOT->ForceStyle();
    gStyle->SetOptFit(0);
    gStyle->SetOptStat(0); 
    gROOT->ProcessLine("#include <vector>"); 

    static const Int_t ftyp =6 ;// Data and MC
    string fname[6]={"DataZeroBiasAllBx","herwigpp","pythia8_Monash","pythia8_MBR","epos","qgsjetII"};
    for (int i=0; i<ftyp;i++){
	cout << " file :"<<i<<" ==> "<<fname[i].c_str()<<endl;
    };
    //gStyle->SetOptStat(111);
    bool save =true;
    
    string filenames[6] ={"root://eoscms.cern.ch//eos/cms/store/user/higgs313/CFFtrees/ZeroBias_byHans/data_RunIILowPU_0T_01072015_data_ZeroBias1_Run2015A_Run247324_byHans.root",
			  "root://eoscms.cern.ch//eos/cms/store/user/zdemirog/13TeV/MC/MinBias_TuneEE5C_13TeV-herwigpp_MagnetOff_trees.root",
			  "root://eoscms.cern.ch//eos/cms/store/user/zdemirog/13TeV/MC/TuneMonash_MagnetOff_TuneMonashMagnetOff.root",
			  "root://eoscms.cern.ch//eos/cms/store/user/zdemirog/13TeV/MC/MinBias_TuneMBR_13TeV-pythia8_MagnetOff_trees.root",
			  "root://eoscms.cern.ch//eos/cms/store/user/zdemirog/13TeV/MC/ReggeGribovPartonMC_13TeV-EPOS_MagnetOff_trees.root",
			  "root://eoscms.cern.ch//eos/cms/store/user/zdemirog/13TeV/MC/ReggeGribovPartonMC_13TeV-QGSJetII_MagnetOff_trees.root"
			  
			  
    };
    
    
    string energyname[13]={"RecHitHCAL","RecHitHF","RecHitECAL","CaloTower",
			   "hcalPFClustersCorrEnergy","ecalPFClustersCorrEnergy","HFPFClustersCorrEnergy",
			   "hcalPFClustersRawEnergy","ecalPFClustersRawEnergy","HFPFClustersRawEnergy",
			   "Gen","Events","CastorTower"};
    
    
   
    
    
    static const Int_t etyp = 13 ;
   
    char title[999];
  
    vector<float> RecHitHCAL; 
    vector<float> RecHitHF;
    vector<float> RecHitECAL; 
    vector<float> RecHit;
    vector<float> CaloTower;
    vector<float> hcalPFClustersCorrEnergy; 
    vector<float> ecalPFClustersCorrEnergy;
    vector<float> HFPFClustersCorrEnergy;
    vector<float> hcalPFClustersRawEnergy;
    vector<float> ecalPFClustersRawEnergy;
    vector<float> HFPFClustersRawEnergy;
    vector<float> PFClusters;
    vector<float> GenDetEventSelect;
    vector<float> CastorTower;

    TFile *file[ftyp+1];
    TFile *fOutFile[ftyp+1];
    TTree *fChain[ftyp+1];

    TTree *EnergyFlow_Det[ftyp+1];
  
    int TotNofEvent[ftyp+1];
  


    int decade = 0;
    for (int f=0; f<ftyp; f++){
    //for (int f=FileNumber; f<FileNumber+1; f++){
	//----------------------Creating tree for output--------------//
	sprintf(title,"EFlow_DetLevel_%s_tree_0Tesla_withCastor.root",fname[f].c_str());
	fOutFile[f]= new TFile(title,"RECREATE");
	//sprintf(title,"%s",fname[f].c_str());
	sprintf(title,"EFlow");
	EnergyFlow_Det[f]= new TTree(title,title);
	EnergyFlow_Det[f]->Branch("RecHitHCAL",&RecHitHCAL); 
	EnergyFlow_Det[f]->Branch("RecHitHF",&RecHitHF);
	EnergyFlow_Det[f]->Branch("RecHitECAL",&RecHitECAL); 
	EnergyFlow_Det[f]->Branch("CaloTower",&CaloTower);
	EnergyFlow_Det[f]->Branch("RecHit",&RecHit);
	EnergyFlow_Det[f]->Branch("hcalPFClustersCorrEnergy",&hcalPFClustersCorrEnergy); 
	EnergyFlow_Det[f]->Branch("ecalPFClustersCorrEnergy",&ecalPFClustersCorrEnergy);
	EnergyFlow_Det[f]->Branch("HFPFClustersCorrEnergy",&HFPFClustersCorrEnergy);
	EnergyFlow_Det[f]->Branch("hcalPFClustersRawEnergy",&hcalPFClustersRawEnergy);
	EnergyFlow_Det[f]->Branch("ecalPFClustersRawEnergy",&ecalPFClustersRawEnergy);
	EnergyFlow_Det[f]->Branch("HFPFClustersRawEnergy",&HFPFClustersRawEnergy);
	EnergyFlow_Det[f]->Branch("PFClusters",&PFClusters);
	EnergyFlow_Det[f]->Branch("GenDetEventSelect",&GenDetEventSelect);
	EnergyFlow_Det[f]->Branch("CastorTower",&CastorTower);
	// --- open file in EOS
	file[f]   = TFile::Open(filenames[f].c_str(),"READ");
      
	cout<<"file : "<<filenames[f].c_str()<<endl;
	// --- read tree
	fChain[f] = (TTree*)file[f]->Get("EflowTree/data");
	//Event
	fChain[f]->SetBranchAddress("run", &run, &b_run);
	fChain[f]->SetBranchAddress("lumi", &lumi, &b_lumi);
	fChain[f]->SetBranchAddress("event", &event, &b_event);
	fChain[f]->SetBranchAddress("genWeight", &genWeight, &b_genWeight);
	fChain[f]->SetBranchAddress("processID", &processID, &b_processID);
	fChain[f]->SetBranchAddress("cmenergy", &cmenergy, &b_cmenergy);
	fChain[f]->SetBranchAddress("puTrueNumInteractions", &puTrueNumInteractions, &b_puTrueNumInteractions);
	fChain[f]->SetBranchAddress("PUNumInteractions", &PUNumInteractions, &b_PUNumInteractions);
	
	std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * genParticlesp4_ = 0;
	if(f>0){
	fChain[f]->SetBranchAddress("genParticlesp4", &genParticlesp4_);
	fChain[f]->SetBranchAddress("genParticlescharge", &genParticlescharge, &b_genParticlescharge);
	fChain[f]->SetBranchAddress("genParticlespdg", &genParticlespdg, &b_genParticlespdg);
	fChain[f]->SetBranchAddress("genParticlesstatus", &genParticlesstatus, &b_genParticlesstatus);
	fChain[f]->SetBranchAddress("Xix", &Xix, &b_Xix);
	fChain[f]->SetBranchAddress("Xiy", &Xiy, &b_Xiy);
	fChain[f]->SetBranchAddress("XiSD", &XiSD, &b_XiSD);
	fChain[f]->SetBranchAddress("XiDD", &XiDD, &b_XiDD);
	}
	fChain[f]->SetBranchAddress("vtxx", &vtxx, &b_vtxx);
	fChain[f]->SetBranchAddress("vtxy", &vtxy, &b_vtxy);
	fChain[f]->SetBranchAddress("vtxz", &vtxz, &b_vtxz);
	fChain[f]->SetBranchAddress("vtxxErr", &vtxxErr, &b_vtxxErr);
	fChain[f]->SetBranchAddress("vtxyErr", &vtxyErr, &b_vtxyErr);
	fChain[f]->SetBranchAddress("vtxzErr", &vtxzErr, &b_vtxzErr);
	fChain[f]->SetBranchAddress("vtxisValid", &vtxisValid, &b_vtxisValid);
	fChain[f]->SetBranchAddress("vtxisFake", &vtxisFake, &b_vtxisFake);
	fChain[f]->SetBranchAddress("vtxchi2", &vtxchi2, &b_vtxchi2);
	fChain[f]->SetBranchAddress("vtxndof", &vtxndof, &b_vtxndof);
	fChain[f]->SetBranchAddress("vtxnTracks", &vtxnTracks, &b_vtxnTracks);
	fChain[f]->SetBranchAddress("simvtxx", &simvtxx, &b_simvtxx);
	fChain[f]->SetBranchAddress("simvtxy", &simvtxy, &b_simvtxy);
	fChain[f]->SetBranchAddress("simvtxz", &simvtxz, &b_simvtxz);
      
	//Triger
	//if (f==0){
	fChain[f]->SetBranchAddress("trgl1L1GTAlgo", &trgl1L1GTAlgo, &b_trgl1L1GTAlgo);
	fChain[f]->SetBranchAddress("trgl1L1GTTech", &trgl1L1GTTech, &b_trgl1L1GTTech);
	fChain[f]->SetBranchAddress("trgZeroBias", &trgZeroBias, &b_trgZeroBias);
	//}
      
	// // PF Candidate
	// std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * PFCandidatesp4_ = 0;
	// fChain[f]->SetBranchAddress("PFCandidatesparticleId", &PFCandidatesparticleId, &b_PFCandidatesparticleId);
	// fChain[f]->SetBranchAddress("PFCandidatesp4", &PFCandidatesp4_);
	// fChain[f]->SetBranchAddress("PFCandidatesrawEcalEnergy", &PFCandidatesrawEcalEnergy, &b_PFCandidatesrawEcalEnergy);
	// fChain[f]->SetBranchAddress("PFCandidatesrawHcalEnergy", &PFCandidatesrawHcalEnergy, &b_PFCandidatesrawHcalEnergy);
	//Calo Tower
	std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * CaloTowersp4_ = 0;
	fChain[f]->SetBranchAddress("CaloTowersp4", &CaloTowersp4_);
	fChain[f]->SetBranchAddress("CaloTowersemEnergy", &CaloTowersemEnergy, &b_CaloTowersemEnergy);
	fChain[f]->SetBranchAddress("CaloTowershadEnergy", &CaloTowershadEnergy, &b_CaloTowershadEnergy);
	fChain[f]->SetBranchAddress("CaloTowershasEB", &CaloTowershasEB, &b_CaloTowershasEB);
	fChain[f]->SetBranchAddress("CaloTowershasEE", &CaloTowershasEE, &b_CaloTowershasEE);
	fChain[f]->SetBranchAddress("CaloTowershasHB", &CaloTowershasHB, &b_CaloTowershasHB);
	fChain[f]->SetBranchAddress("CaloTowershasHE", &CaloTowershasHE, &b_CaloTowershasHE);
	fChain[f]->SetBranchAddress("CaloTowershasHF", &CaloTowershasHF, &b_CaloTowershasHF);
	// Rec Hit
	fChain[f]->SetBranchAddress("EcalRecHitenergy", &EcalRecHitenergy, &b_EcalRecHitenergy);
	fChain[f]->SetBranchAddress("EcalRecHitEt", &EcalRecHitEt, &b_EcalRecHitEt);
	fChain[f]->SetBranchAddress("EcalRecHittime", &EcalRecHittime, &b_EcalRecHittime);
	fChain[f]->SetBranchAddress("EcalRecHitieta", &EcalRecHitieta, &b_EcalRecHitieta);
	fChain[f]->SetBranchAddress("EcalRecHitiphi", &EcalRecHitiphi, &b_EcalRecHitiphi);
	fChain[f]->SetBranchAddress("EcalRecHiteta", &EcalRecHiteta, &b_EcalRecHiteta);
	fChain[f]->SetBranchAddress("EcalRecHitphi", &EcalRecHitphi, &b_EcalRecHitphi);
      
	fChain[f]->SetBranchAddress("HBHERecHitenergy", &HBHERecHitenergy, &b_HBHERecHitenergy);
	fChain[f]->SetBranchAddress("HBHERecHitEt", &HBHERecHitEt, &b_HBHERecHitEt);
	fChain[f]->SetBranchAddress("HBHERecHittime", &HBHERecHittime, &b_HBHERecHittime);
	fChain[f]->SetBranchAddress("HBHERecHitieta", &HBHERecHitieta, &b_HBHERecHitieta);
	fChain[f]->SetBranchAddress("HBHERecHitiphi", &HBHERecHitiphi, &b_HBHERecHitiphi);
	fChain[f]->SetBranchAddress("HBHERecHitdepth", &HBHERecHitdepth, &b_HBHERecHitdepth);
	//fChain[f]->SetBranchAddress("HBHERecHitHBHENumRecHits", &HBHERecHitHBHENumRecHits, &b_HBHERecHitHBHENumRecHits);
	fChain[f]->SetBranchAddress("HBHERecHiteta", &HBHERecHiteta, &b_HBHERecHiteta);
	fChain[f]->SetBranchAddress("HBHERecHitphi", &HBHERecHitphi, &b_HBHERecHitphi);
	fChain[f]->SetBranchAddress("HFRecHitenergy", &HFRecHitenergy, &b_HFRecHitenergy);
	fChain[f]->SetBranchAddress("HFRecHitEt", &HFRecHitEt, &b_HFRecHitEt);
	fChain[f]->SetBranchAddress("HFRecHittime", &HFRecHittime, &b_HFRecHittime);
	fChain[f]->SetBranchAddress("HFRecHitieta", &HFRecHitieta, &b_HFRecHitieta);
	fChain[f]->SetBranchAddress("HFRecHitiphi", &HFRecHitiphi, &b_HFRecHitiphi);
	fChain[f]->SetBranchAddress("HFRecHitdepth", &HFRecHitdepth, &b_HFRecHitdepth);
	//fChain[f]->SetBranchAddress("HFRecHitHFNumRecHits", &HFRecHitHFNumRecHits, &b_HFRecHitHFNumRecHits);
	fChain[f]->SetBranchAddress("HFRecHiteta", &HFRecHiteta, &b_HFRecHiteta);
	fChain[f]->SetBranchAddress("HFRecHitphi", &HFRecHitphi, &b_HFRecHitphi);

	//Castor RecHit
	fChain[f]->SetBranchAddress("CastorRecHitEnergy", &CastorRecHitEnergy, &b_CastorRecHitEnergy);
	fChain[f]->SetBranchAddress("CastorRecHitSector", &CastorRecHitSector, &b_CastorRecHitSector);
	fChain[f]->SetBranchAddress("CastorRecHitModule", &CastorRecHitModule, &b_CastorRecHitModule);
        fChain[f]->SetBranchAddress("CastorRecHitisBad", &CastorRecHitisBad, &b_CastorRecHitisBad);
	fChain[f]->SetBranchAddress("CastorRecHitisSaturated", &CastorRecHitisSaturated, &b_CastorRecHitisSaturated);
	fChain[f]->SetBranchAddress("CastorRecHitisDesaturated", &CastorRecHitisDesaturated, &b_CastorRecHitisDesaturated);
	//Castor Tower
	std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > * CastorTowerp4_ = 0;
	fChain[f]->SetBranchAddress("CastorTowerp4", &CastorTowerp4_);
	fChain[f]->SetBranchAddress("CastorToweremEnergy", &CastorToweremEnergy, &b_CastorToweremEnergy);
	fChain[f]->SetBranchAddress("CastorTowerhadEnergy", &CastorTowerhadEnergy, &b_CastorTowerhadEnergy);
	fChain[f]->SetBranchAddress("CastorTowerNrechits", &CastorTowerNrechits, &b_CastorTowerNrechits);

	//PF Clusters
	fChain[f]->SetBranchAddress("hcalPFClustersenergy", &hcalPFClustersenergy, &b_hcalPFClustersenergy);
	fChain[f]->SetBranchAddress("hcalPFClusterscorrectedEnergy", &hcalPFClusterscorrectedEnergy, &b_hcalPFClusterscorrectedEnergy);
	fChain[f]->SetBranchAddress("hcalPFClusterscorrectedEnergyUncertainty", &hcalPFClusterscorrectedEnergyUncertainty, &b_hcalPFClusterscorrectedEnergyUncertainty);
	fChain[f]->SetBranchAddress("hcalPFClusterstime", &hcalPFClusterstime, &b_hcalPFClusterstime);
	fChain[f]->SetBranchAddress("hcalPFClustersdepth", &hcalPFClustersdepth, &b_hcalPFClustersdepth);
	fChain[f]->SetBranchAddress("hcalPFClusterspt", &hcalPFClusterspt, &b_hcalPFClusterspt);
	fChain[f]->SetBranchAddress("hcalPFClustersEt", &hcalPFClustersEt, &b_hcalPFClustersEt);
	fChain[f]->SetBranchAddress("hcalPFClusterseta", &hcalPFClusterseta, &b_hcalPFClusterseta);
	fChain[f]->SetBranchAddress("hcalPFClustersphi", &hcalPFClustersphi, &b_hcalPFClustersphi);
	fChain[f]->SetBranchAddress("hcalPFClusterssize", &hcalPFClusterssize, &b_hcalPFClusterssize);
	fChain[f]->SetBranchAddress("hcalPFClustersisInClean", &hcalPFClustersisInClean, &b_hcalPFClustersisInClean);
	fChain[f]->SetBranchAddress("hcalPFClustersisInUnClean", &hcalPFClustersisInUnClean, &b_hcalPFClustersisInUnClean);
	fChain[f]->SetBranchAddress("hfPFClustersenergy", &hfPFClustersenergy, &b_hfPFClustersenergy);
	fChain[f]->SetBranchAddress("hfPFClusterscorrectedEnergy", &hfPFClusterscorrectedEnergy, &b_hfPFClusterscorrectedEnergy);
	fChain[f]->SetBranchAddress("hfPFClusterscorrectedEnergyUncertainty", &hfPFClusterscorrectedEnergyUncertainty, &b_hfPFClusterscorrectedEnergyUncertainty);
	fChain[f]->SetBranchAddress("hfPFClusterstime", &hfPFClusterstime, &b_hfPFClusterstime);
	fChain[f]->SetBranchAddress("hfPFClustersdepth", &hfPFClustersdepth, &b_hfPFClustersdepth);
	fChain[f]->SetBranchAddress("hfPFClusterspt", &hfPFClusterspt, &b_hfPFClusterspt);
	fChain[f]->SetBranchAddress("hfPFClustersEt", &hfPFClustersEt, &b_hfPFClustersEt);
	fChain[f]->SetBranchAddress("hfPFClusterseta", &hfPFClusterseta, &b_hfPFClusterseta);
	fChain[f]->SetBranchAddress("hfPFClustersphi", &hfPFClustersphi, &b_hfPFClustersphi);
	fChain[f]->SetBranchAddress("hfPFClusterssize", &hfPFClusterssize, &b_hfPFClusterssize);
	fChain[f]->SetBranchAddress("hfPFClustersisInClean", &hfPFClustersisInClean, &b_hfPFClustersisInClean);
	fChain[f]->SetBranchAddress("hfPFClustersisInUnClean", &hfPFClustersisInUnClean, &b_hfPFClustersisInUnClean);
	fChain[f]->SetBranchAddress("ecalPFClustersenergy", &ecalPFClustersenergy, &b_ecalPFClustersenergy);
	fChain[f]->SetBranchAddress("ecalPFClusterscorrectedEnergy", &ecalPFClusterscorrectedEnergy, &b_ecalPFClusterscorrectedEnergy);
	fChain[f]->SetBranchAddress("ecalPFClusterscorrectedEnergyUncertainty", &ecalPFClusterscorrectedEnergyUncertainty, &b_ecalPFClusterscorrectedEnergyUncertainty);
	fChain[f]->SetBranchAddress("ecalPFClusterstime", &ecalPFClusterstime, &b_ecalPFClusterstime);
	fChain[f]->SetBranchAddress("ecalPFClustersdepth", &ecalPFClustersdepth, &b_ecalPFClustersdepth);
	fChain[f]->SetBranchAddress("ecalPFClusterspt", &ecalPFClusterspt, &b_ecalPFClusterspt);
	fChain[f]->SetBranchAddress("ecalPFClustersEt", &ecalPFClustersEt, &b_ecalPFClustersEt);
	fChain[f]->SetBranchAddress("ecalPFClusterseta", &ecalPFClusterseta, &b_ecalPFClusterseta);
	fChain[f]->SetBranchAddress("ecalPFClustersphi", &ecalPFClustersphi, &b_ecalPFClustersphi);
	fChain[f]->SetBranchAddress("ecalPFClusterssize", &ecalPFClusterssize, &b_ecalPFClusterssize);
	fChain[f]->SetBranchAddress("ecalPFClustersisInClean", &ecalPFClustersisInClean, &b_ecalPFClustersisInClean);
	fChain[f]->SetBranchAddress("ecalPFClustersisInUnClean", &ecalPFClustersisInUnClean, &b_ecalPFClustersisInUnClean);
	fChain[f]->SetBranchAddress("bx", &bx, &b_bx);

	// ----------------------- Cut-------------------------//
	lumimin =88;
	lumimax =1000;
	emin = 5.;
	CastorNoiseThreshold = 2./sqrt(5);
	Etabnd = 5.191;//Max Eta for CMS
	//Etabnd = 6.6;//Max Eta for CMS
	etamin =3.139;
	etamax =4.889;//event select
	etamaxMinus =-3.139;
	etaminMinus =-4.889;//event select
	//etamax =5.191;//event select 
	minXiSD=1e-6;
	// ----------------------- Event -----------------------//
  
	Long64_t nentries = fChain[f]->GetEntriesFast();
	cout<<"Entries "<<nentries<<endl;
  
  
	Long64_t nbytes = 0, nb = 0;

	TotNofEvent[f]= 0;
	

	//int maxevent=10000;
	for (Long64_t ev=0; ev<nentries;ev++) {
      
	//    for (Long64_t ev=0; ev<maxevent;ev++) {
	
	    Long64_t iev = fChain[f]->LoadTree(ev);
	    if (iev < 0)break;
	    nb = fChain[f]->GetEntry(ev);   nbytes += nb;

	    double progress = 10.0*ev/(1.0*nentries);
	    int k = TMath::FloorNint(progress); 
	    if (k > decade) 
		cout<<10*k<<" %"<<endl;
	    decade = k; 
	    RecHit.clear(); 
	    RecHitHCAL.clear(); 
	    RecHitHF.clear();
	    RecHitECAL.clear(); 
	    CaloTower.clear();
	    hcalPFClustersCorrEnergy.clear(); 
	    ecalPFClustersCorrEnergy.clear();
	    HFPFClustersCorrEnergy.clear();
	    hcalPFClustersRawEnergy.clear();
	    ecalPFClustersRawEnergy.clear();
	    HFPFClustersRawEnergy.clear();
	    PFClusters.clear();
	    GenDetEventSelect.clear();
	    CastorTower.clear();	   
	    for (int i =0; i<nEtaBins;i++) {
		RecHitHCALEtaSums[i]=0.;
	   
		RecHitECALEtaSums[i]=0.;
		RecHitHFEtaSums[i]=0.;
		CaloEtaSums[i]=0.;
		CastorTowerEtaSums[i]=0.;
		//PFCandEtaSums[i]=0.;
 
		PFClustersEtaSums[i]=0.;
		PFClustersECALEtaSums[i]=0.;
		PFClustersHCALEtaSums[i]=0.;
		PFClustersHFEtaSums[i]=0.;
	
		PFClustersEtaSumsUp[i]=0.;
		PFClustersECALEtaSumsUp[i]=0.;
		PFClustersHCALEtaSumsUp[i]=0.;
		PFClustersHFEtaSumsUp[i]=0.;
	
		PFClustersEtaSumsLo[i]=0.;
		PFClustersECALEtaSumsLo[i]=0.;
		PFClustersHCALEtaSumsLo[i]=0.;
		PFClustersHFEtaSumsLo[i]=0.;
	  
		PFClustersEtaSumsRaw[i]=0.;
		PFClustersECALEtaSumsRaw[i]=0.;
		PFClustersHCALEtaSumsRaw[i]=0.;
		PFClustersHFEtaSumsRaw[i]=0.;
		
		GenEtaSumsDetEvntSelct[i]=0.;
			
	    }
      
	    // Ini. for each event
	    EnergyCutRecHit=false;
	    EnergyCutRecHitMinus=false;
	    EnergyCutTowerMinus=false;
	    EnergyCutTowerPlus=false;
	    EnergyCutTower=false;
	    EnergyCutRecHitPlus=false;
	    EnergyCutPFCluster=false;
	    EnergyCutRecHitHFAnd=false;
	    RunCut=false;
	    LumiCut=false;
	    bxCut=false;
      
      
	    // if (f==0 && run==251721){
	    if (f==0 && run==247324) RunCut=true;
	    if(f>0) RunCut =true;// for MC
            
	    // ----------------------- fat bunch ------------------//
	    // if (f==0 && bx==208) bxCut=true;
	    bxCut =true;// for MC
            
	    // ----------------------- lumi cut ------------------//
      
	    if (f==0)LumiCut=(lumi>=lumimin &&lumi<lumimax);
	    else LumiCut=true;// for MC
      
	    //if(LumiCut && RunCut ){
	    if(RunCut && LumiCut && bxCut){
	  
		// ----------------------- triger cut --------------//
		if (f==0)TrigerPass =  (trgZeroBias== 1);
		else TrigerPass=true;
	  
		if(TrigerPass){
		    //-- Event Selection for Det Level --//
			
			/////-------from Sebastian Castor event selection ------/////	
			//castorEventSelection = False
			//for i in xrange(0, self.fChain.CastorTowerp4.size()):
			//if self.fChain.CastorTowerp4.at(i).energy() > self.CastorNoiseThreshold*math.sqrt(self.fChain.CastorTowerNrechits.at(i)):
       			//castorEventSelection = True
       			///break

		        for(unsigned long cstr=0; cstr<CastorTowerp4_->size(); cstr++){
			XYZTVector cstrtwr = (*CastorTowerp4_)[cstr];
   			if(cstrtwr.E() > CastorNoiseThreshold * sqrt(CastorTowerNrechits->at(cstr))) {
			    EnergyCutTower=true;
			}
		    }

		    //--------- HF OR-------//
		    //for(unsigned long cal=0; cal<CaloTowersp4_->size(); cal++){
		    //XYZTVector caltwr = (*CaloTowersp4_)[cal];
		    ///if((abs(caltwr.Eta())>=etamin && abs(caltwr.Eta())<=etamax) && caltwr.E() > emin) {
		    //   EnergyCutTower=true;
		    ///	}
		    ///  }
		    if (EnergyCutTower){
			// Gen Level Event selection for Detlevel
			if (f>0){
			    for (unsigned long gd=0; gd<genParticlesp4_->size(); gd++){
				XYZTVector genDet = (*genParticlesp4_)[gd];
			  
				if((abs(genDet.Eta())<= Etabnd)  ) {
				    selcetetabin=getBin(genDet.Eta(),EtaBins, nEtaBins);
				    GenEtaSumsDetEvntSelct[selcetetabin] = GenEtaSumsDetEvntSelct[selcetetabin] + genDet.E();
				}
			    }//Gen
			}
			// ----------------------- ECALRecHit --------------- //
			for(unsigned long j=0; j<EcalRecHitenergy->size(); j++) {
			    selcetetabin=getBin(EcalRecHiteta->at(j),EtaBins,nEtaBins);
			    RecHitECALEtaSums[selcetetabin]= RecHitECALEtaSums[selcetetabin] + EcalRecHitenergy->at(j);
			}  
		  
			// ----------------------- HCALRecHit --------------- //
			for(unsigned long j=0; j<HBHERecHitenergy->size(); j++) {
			    selcetetabin=getBin(HBHERecHiteta->at(j),EtaBins,nEtaBins);
			    RecHitHCALEtaSums[selcetetabin]= RecHitHCALEtaSums[selcetetabin] + HBHERecHitenergy->at(j);
			}
		  
			// ----------------------- HFRecHit --------------- //
			for(unsigned long j=0; j<HFRecHitenergy->size(); j++) {
			    if((abs(HFRecHiteta->at(j))>=etamin && abs(HFRecHiteta->at(j))<=Etabnd)) {
				selcetetabin=getBin(HFRecHiteta->at(j),EtaBins,nEtaBins);
				RecHitHFEtaSums[selcetetabin]= RecHitHFEtaSums[selcetetabin] + HFRecHitenergy->at(j);
			    }
			}  
			//----------------------- CaloTower  -------------//
			for (unsigned long cal=0; cal<CaloTowersp4_->size(); cal++){
		      
			    XYZTVector caltwr = (*CaloTowersp4_)[cal];
			    selcetetabin=getBin(caltwr.Eta(),EtaBins,nEtaBins);
			    CaloEtaSums[selcetetabin]= CaloEtaSums[selcetetabin] + caltwr.E();
			}
		  
			// // -----------------------  PF cand  -----------------------//
			// //PFCand
			// for (unsigned long pf=0; pf<PFCandidatesp4_->size(); pf++){
			// 	XYZTVector pfcand = (*PFCandidatesp4_)[pf];
			// 	//cout << " pf energy "<<pfcand.E()<< " pf eta "<< pfcand.Eta()<<endl;
		  
			// 	// if(pfcand.E() > 10.) {
			// 	//cout <<"event "<< ev <<" PFCandidates "<<PFCandidatesp4_->size()<<endl; 
			// 	selcetetabin=getBin(pfcand.Eta(),EtaBins, nEtaBins);
		  
			// 	PFCandEtaSums[selcetetabin]= PFCandEtaSums[selcetetabin] + pfcand.E();
		  
			// 	//cout<<" eta "<<pfcand.Eta()<<" bin "<<selcetetabin<<" energy " << pfcand.E() <<" total PF energy "<<PFCandEtaSums[selcetetabin]<<endl;
			// 	// }
			// }//PFCand
		  
			//----------------------- PF Cluster --------------- //
			//HCALcorrected energy
			for(unsigned long pfc=0; pfc<hcalPFClusterscorrectedEnergy->size(); pfc++) {
			    selcetetabin=getBin(hcalPFClusterseta->at(pfc),EtaBins, nEtaBins);
			    PFClustersHCALEtaSums[selcetetabin]= PFClustersHCALEtaSums[selcetetabin]+hcalPFClusterscorrectedEnergy->at(pfc);
			}
			//Ecal corrected energy
			for(unsigned long pfc=0; pfc<ecalPFClusterscorrectedEnergy->size(); pfc++) {
			    selcetetabin=getBin(ecalPFClusterseta->at(pfc),EtaBins, nEtaBins);
			    PFClustersECALEtaSums[selcetetabin]= PFClustersECALEtaSums[selcetetabin]+ ecalPFClusterscorrectedEnergy->at(pfc);
			}
			//Hf corrected energy	   
			for(unsigned long pfc=0; pfc<hfPFClusterscorrectedEnergy->size(); pfc++) {
			    if((abs(hfPFClusterseta->at(pfc))>=etamin && abs(hfPFClusterseta->at(pfc))<=Etabnd)) {
				selcetetabin=getBin(hfPFClusterseta->at(pfc),EtaBins, nEtaBins);
				PFClustersHFEtaSums[selcetetabin]= PFClustersHFEtaSums[selcetetabin]+hfPFClusterscorrectedEnergy->at(pfc);
			    }
			}
		  
			//HCAL raw energy
			for(unsigned long pfc=0; pfc<hcalPFClustersenergy->size(); pfc++) {
			    selcetetabin=getBin(hcalPFClusterseta->at(pfc),EtaBins, nEtaBins);
			    PFClustersHCALEtaSumsRaw[selcetetabin]= PFClustersHCALEtaSumsRaw[selcetetabin]+hcalPFClustersenergy->at(pfc);
		      
			}
			//ECAL raw energy
			for(unsigned long pfc=0; pfc< ecalPFClustersenergy->size(); pfc++) {
			    selcetetabin=getBin(ecalPFClusterseta->at(pfc),EtaBins, nEtaBins);
			    PFClustersECALEtaSumsRaw[selcetetabin]= PFClustersECALEtaSumsRaw[selcetetabin]+ecalPFClustersenergy->at(pfc);
			}
			//HF raw energy
			for(unsigned long pfc=0; pfc<hfPFClustersenergy->size(); pfc++) {
		      
			    if((abs(hfPFClusterseta->at(pfc))>=etamin && abs(hfPFClusterseta->at(pfc))<=Etabnd) ) { 
				selcetetabin=getBin(hfPFClusterseta->at(pfc),EtaBins, nEtaBins);
				PFClustersHFEtaSumsRaw[selcetetabin]= PFClustersHFEtaSumsRaw[selcetetabin]+hfPFClustersenergy->at(pfc);
			    }
			}

			//----------------------- Castor Tower  -------------//

			//totalCastorEnergy = 0.
			//for i in xrange(0, self.fChain.CastorTowerp4.size()):
  			//if self.fChain.CastorTowerp4.at(i).energy() > self.CastorNoiseThreshold*math.sqrt(self.fChain.CastorTowerNrechits.at(i)):
  			//totalCastorEnergy += self.fChain.CastorTowerp4.at(i).energy()


			for (unsigned long cas=0; cas<CastorTowerp4_->size(); cas++){
		      
			    XYZTVector castwr = (*CastorTowerp4_)[cas];
			    selcetetabin=getBin(castwr.Eta(),EtaBins,nEtaBins);
			    CastorTowerEtaSums[selcetetabin]= CastorTowerEtaSums[selcetetabin] + castwr.E();
			}

		  
			// Filling tree
			float totenergyrechit,totenergypfclusters;
			for (int k=0;k<nEtaBins;k++){
			   			    // (HFPFClustersRawEnergy[k]).push_back(PFClustersHFEtaSumsRaw[k]);
			    // (Gen_DetEvntSelct[k]).push_back(GenEtaSumsDetEvntSelct[k]);
			    totenergyrechit =0.;
			    totenergypfclusters=0.;
			    RecHitHCAL.push_back(RecHitHCALEtaSums[k]);
			    RecHitHF.push_back(RecHitHFEtaSums[k]);
			    RecHitECAL.push_back(RecHitECALEtaSums[k]); 
			    totenergyrechit = RecHitHCALEtaSums[k]+RecHitECALEtaSums[k]+RecHitHFEtaSums[k];
			    RecHit.push_back(totenergyrechit);
			    CaloTower.push_back(CaloEtaSums[k]); 
			    CastorTower.push_back(CastorTowerEtaSums[k]); 
			    hcalPFClustersCorrEnergy.push_back(PFClustersHCALEtaSums[k]); 
			    ecalPFClustersCorrEnergy.push_back(PFClustersECALEtaSums[k]);
			    HFPFClustersCorrEnergy.push_back(PFClustersHFEtaSums[k]);
			    hcalPFClustersRawEnergy.push_back(PFClustersHCALEtaSumsRaw[k]);
			    ecalPFClustersRawEnergy.push_back(PFClustersECALEtaSumsRaw[k]);
			    HFPFClustersRawEnergy.push_back(PFClustersHFEtaSumsRaw[k]);
			    totenergypfclusters = PFClustersECALEtaSums[k]+PFClustersHCALEtaSumsRaw[k]+PFClustersHFEtaSumsRaw[k]+CastorTowerEtaSums[k];
			    PFClusters.push_back(totenergypfclusters);
			    GenDetEventSelect.push_back(GenEtaSumsDetEvntSelct[k]);
			    
			}
		  
			TotNofEvent[f]++;
			EnergyFlow_Det[f]->Fill(); 
		    }//HF OR Energy Cut
		}//Trigerpass
	    }//Lumi && Run && bnx Cut
     

	   
	}//Event
	//cout <<filenames[f].c_str()<<"  Total event : "<<TotNofEvent[f]<<endl;
	fOutFile[f]->Write();
	delete fOutFile[f];
	cout<<"Filling tree and write in root file with "<<TotNofEvent[f]<<" events"<<" for file : "<<fname[f].c_str()<<endl;
    }//File
}
void track_selection_tree_1()
{
   //gROOT->ProcessLine(".L Loader.C+");

    // attach "UETree/data" of tree1.root as the main root file for this program
    TFile *myFile = TFile::Open("tree1.root", "READ");
    TTree* tree = (TTree*)myFile->Get("UETree/data");

    //for this dataset we want lumisection of 90 and above
    //data from branch 62
    int nlumi_section;
    tree->SetBranchAddress("lumi", &nlumi_section);

    int iZeroBias; //data from Branch 60
    tree->SetBranchAddress("trgZeroBias",&iZeroBias);

    //variables to check if there is only 1 vertex
    vector<float> *fvecVtxz = 0; //require initialisation to 0 to avoid crash
    tree->SetBranchAddress("vtxz",&fvecVtxz);
    float fvecVtxz_size;

    //variables to check for within 15cm
    vector<float> *fvecVtxzBS = 0; //from branch 54
    tree->SetBranchAddress("vtxzBS", &fvecVtxzBS);
    float nBeamSize;

    vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > > *tracks = 0;
    tree->SetBranchAddress("recoTracksp4", &tracks);
    //vector<TLorentzVector> *tracks = new vector<TLorentzVector>;

    vector<float> *fVec_dz = 0;
    tree->SetBranchAddress ("recoTracksdz", &fVec_dz);
    vector<float> *fVec_dzErr = 0;
    tree->SetBranchAddress ("recoTracksdzErr", &fVec_dzErr);

    vector<float> *fVec_d0 = 0;
    tree->SetBranchAddress ("recoTracksd0", &fVec_d0);
    vector<float> *fVec_d0Err = 0;
    tree->SetBranchAddress ("recoTracksd0Err", &fVec_d0Err);

    vector<float> *fVec_ptErr = 0;
    tree->SetBranchAddress("recoTracksptErr", &fVec_ptErr);

    vector<int> *nVec_HighPurity = 0;
    tree->SetBranchAddress ("recoTrackshighPurity", &nVec_HighPurity);

    //declare variable to hold track number
    int ntrk, nMulti;
    int ntrk_normalized = 0;
    int nHigh_Purity = 0;
    float dz_dzErr, d0_d0Err, pt_ptErr;

    const int lumi_cut = 90;
    const double eta_cut = 2.4;
    const double pt_cut = 0.5;
    const double vtxz_number = 1.;
    const double vtxz_size = 10;
    const int ntracks = 533084;


    TCanvas *canvas = new TCanvas;
    //TH1F *event_histo = new TH1F ("reco_evt", "reco_evt", 100, 0, 200);
    TH1F *pt_histo = new TH1F ("reco_pt", "Normalized_reco_pT", 100, 0, 100);
    TH1F *eta_histo = new TH1F ("reco_eta", "Normalized_reco_Eta", 25, -3, 3);
    TH1F *phi_histo = new TH1F ("reco_phi", "Normalized_reco_Phi", 100, -4, 4);
    TH1F *lumi_histo = new TH1F ("lumi_section", "lumi_section", 160, 80, 230);
    TH1F *multiplicity = new TH1F ("multiplicity", "Normalized_Multiplicity", 200, 0, 200);
    TH1F *dz_sigmadz = new TH1F ("dz_sigmadz", "Normalized_dz_sigmadz", 200, 0, 200);
    TH1F *d0_sigmad0 = new TH1F ("d0_sigmad0", "Normalized_d0_sigmad0", 200, 0, 200);
    TH1F *pt_sigmapt = new TH1F ("pt_sigmapt", "Normalized_pt_sigmapt", 200, 0, 200);
    //TH1F *normalized_multiplicity_histo = new TH1F ("normalized_multiplicity", "normalized_multiplicity", 200, 0, 200);

    //select events with only 1 vertex using information from Branch 46/47/48. Here we use Branch 48 (z-axis)
    Int_t nEvt = (Int_t)tree->GetEntries();
    cout << "Tree Entries " << nEvt << endl;


    //start loop over events
    for(Int_t i = 0; i < nEvt; ++i)
    {
        //if (i%10000 == 0)
            //cout<< "Processing event number: " << i << endl; //1 TTree entry = 1 event
        cout << "Entry " << i << endl;
        tree -> GetEntry(i);
        cout << "set branch address for zero bias" << endl;

        //selects for events from lumisection >= 90
        if (nlumi_section >= lumi_cut)
        {
            cout << "lumisection is " << nlumi_section << endl;


            //we select only events that are triggered by ZeroBias Trigger. "True" in ZeroBias evaluate to 1
            if (iZeroBias == 1)
            {
                cout << "track pass zero bias" << endl;
                fvecVtxz_size = fvecVtxz->size();
                //vtxz_plot->Fill(fvecVtxz_size);

                if (fvecVtxz_size == vtxz_number)
                {
                    cout << "number of vertex for event " << i << " is " << fvecVtxz_size << endl;

                    //looping over vertices
                    for (int k = 0; k != fvecVtxz_size; ++k)
                    {
                        nBeamSize = fabs((*fvecVtxz)[k] - (*fvecVtxzBS)[0]);
                        cout << "Beam Size is " << nBeamSize << endl;

                        if (nBeamSize <= vtxz_size)
                        {
                            ntrk = tracks->size();

                            //fill with the lumi sections that meet the above event-level cuts
                            lumi_histo->Fill(nlumi_section);

                            nMulti = 0;

                            //looping over tracks
                            for (int j = 0; j != ntrk; ++j)
                            {
                                XYZTVector vec = (*tracks)[j];
                                dz_dzErr = ((*fVec_dz)[j])/((*fVec_dzErr)[j]);
                                d0_d0Err = ((*fVec_d0)[j])/((*fVec_d0Err)[j]);
                                pt_ptErr = ((vec.Pt())/(*fVec_ptErr)[j]);

                                if ((*nVec_HighPurity)[j] == 1)
                                {
                                    if (abs (vec.Eta()) <= eta_cut && vec.Pt() >= pt_cut)
                                    {
                                        phi_histo->Fill(vec.Phi());
                                        pt_histo->Fill(vec.Pt());
                                        eta_histo->Fill(vec.Eta());
                                        dz_sigmadz->Fill(dz_dzErr);
                                        d0_sigmad0->Fill(d0_d0Err);
                                        pt_sigmapt->Fill(pt_ptErr);
                                        ++nMulti;
                                    }
                                    ++nHigh_Purity;
                                }



                                /*if (abs (vec.Eta()) <= eta_cut && vec.Pt() >= pt_cut)
                                {
                                    pt_histo->Fill(vec.Pt());
                                }

                                if (vec.Pt() >= pt_cut)
                                {
                                    eta_histo->Fill(vec.Eta());
                                }*/


                            }

                            multiplicity->Fill(nMulti);
                            ntrk_normalized += nMulti;
                        }


                    }

                }

            }

        }

    }

    cout << "Total number of selected tracks is " << ntrk_normalized << endl;

//vtxz_plot->Draw();
//canvas->Update();
//canvas->SaveAs("vtxz_number.png");
//delete canvas;
//delete vtxz_plot;


    //after the loop over all events, draw the resulting plots

    canvas->Divide(2,3);
    /*canvas->cd(1);
    gPad->SetLogy();
    dz_sigmadz->DrawNormalized("", 1);

    canvas->cd(2);
    gPad->SetLogy();
    d0_sigmad0->DrawNormalized("", 1);

    gPad->SetLogy();
    pt_sigmapt->DrawNormalized("", 1);
    canvas->Update();*/

    canvas->cd(1);
    gPad->SetLogy();
    pt_histo->DrawNormalized("", 1);
    //canvas->Update();

    canvas->cd(2);
    gPad->SetLogy();
    eta_histo->DrawNormalized("", 1);
    //canvas->Update();

    canvas->cd(3);
    gPad->SetLogy();
    phi_histo->DrawNormalized("",1);
    //canvas->Update();

    canvas->cd(4);
    gPad->SetLogy();
    dz_sigmadz->DrawNormalized("", 1);

    canvas->cd(5);
    gPad->SetLogy();
    d0_sigmad0->DrawNormalized("", 1);

    canvas->cd(6);
    gPad->SetLogy();
    pt_sigmapt->DrawNormalized("", 1);
    canvas->Update();

    canvas->SaveAs("tree_1_relative_errors.pdf");
}