Example #1
0
int Fun4All_G4_Prototype3(int nEvents = 1)
{

  gSystem->Load("libfun4all");
  gSystem->Load("libg4detectors");
  gSystem->Load("libg4testbench");
  gSystem->Load("libg4histos");
  gSystem->Load("libg4eval.so");
  gSystem->Load("libqa_modules");

  bool cemc_on = true;
  bool cemc_cell = cemc_on && true;
  bool cemc_twr = cemc_cell && true;
  bool cemc_digi = cemc_twr && true;
  bool cemc_twrcal = cemc_digi && true;
  bool ihcal_on = true;
  bool ihcal_cell = ihcal_on && false;
  bool ihcal_twr = ihcal_cell && false;
  bool ihcal_digi = ihcal_twr && false;
  bool ihcal_twrcal = ihcal_digi && false;
  bool ohcal_on = true;
  bool ohcal_cell = ohcal_on && false;
  bool ohcal_twr = ohcal_cell && false;
  bool ohcal_digi = ohcal_twr && false;
  bool ohcal_twrcal =  ohcal_digi && false;
  bool cryo_on = true;
  bool bh_on = false; // the surrounding boxes need some further thinking
  bool dstreader = true;
  bool hit_ntuple = false;
  bool dstoutput = false;

  ///////////////////////////////////////////
  // Make the Server
  //////////////////////////////////////////
  Fun4AllServer *se = Fun4AllServer::instance();
  se->Verbosity(1);
  recoConsts *rc = recoConsts::instance();
  // only set this if you want a fixed random seed to make
  // results reproducible for testing
//    rc->set_IntFlag("RANDOMSEED",12345678);

  // simulated setup sits at eta=1, theta=40.395 degrees
  double theta = 90-46.4;
  // shift in x with respect to midrapidity setup
  double add_place_x = 183.-173.93+2.54/2.;
  // Test beam generator
  PHG4SimpleEventGenerator *gen = new PHG4SimpleEventGenerator();
  gen->add_particles("e-", 1); // mu-,e-,anti_proton,pi-
  gen->set_vertex_distribution_mean(0.0, 0.0, 0);
  gen->set_vertex_distribution_width(0.0, .7, .7); // Rough beam profile size @ 16 GeV measured by Abhisek
  gen->set_vertex_distribution_function(PHG4SimpleEventGenerator::Gaus,
					PHG4SimpleEventGenerator::Gaus, 
                                        PHG4SimpleEventGenerator::Gaus); // Gauss beam profile
  double angle = theta*TMath::Pi()/180.;
  double eta = -1.*TMath::Log(TMath::Tan(angle/2.));
  gen->set_eta_range(eta-0.001,eta+0.001); // 1mrad angular divergence
  gen->set_phi_range(-0.001, 0.001); // 1mrad angular divergence
  const double momentum = 32;
  gen->set_p_range(momentum,momentum, momentum*2e-2); // 2% momentum smearing
  se->registerSubsystem(gen);

  PHG4ParticleGenerator *pgen = new PHG4ParticleGenerator();
  pgen->set_name("geantino");
  //pgen->set_name(particle);
  pgen->set_vtx(0, 0, 0);
  //pgen->set_vtx(0, ypos, 0);
  double angle = theta*TMath::Pi()/180.;
  double eta = -1.*TMath::Log(TMath::Tan(angle/2.));
  pgen->set_eta_range(0.2*eta, 1.8*eta);
  //pgen->set_phi_range(-0.001, 0.001); // 1mrad angular diverpgence
  //pgen->set_phi_range(-0.5/180.*TMath::Pi(), 0.5/180.*TMath::Pi());
  //pgen->set_eta_range(-1., 1.);
  //pgen->set_phi_range(-0./180.*TMath::Pi(), 0./180.*TMath::Pi());
  pgen->set_phi_range(-20/180.*TMath::Pi(), 20/180.*TMath::Pi());
  pgen->set_mom_range(1, 1);
  //  se->registerSubsystem(pgen);

  // Simple single particle generator
  PHG4ParticleGun *gun = new PHG4ParticleGun();
  gun->set_name("geantino");
  //  gun->set_name("proton");
  gun->set_vtx(0, 0, 0);
  double angle = theta*TMath::Pi()/180.;
  gun->set_mom(sin(angle),0.,cos(angle));
//  se->registerSubsystem(gun);


  PHG4Reco* g4Reco = new PHG4Reco();
  g4Reco->set_field(0);
  //  g4Reco->SetPhysicsList("QGSP_BERT_HP"); // uncomment this line to enable the high-precision neutron simulation physics list, QGSP_BERT_HP

  //----------------------------------------
  // EMCal G4
  //----------------------------------------
  if (cemc_on)
    {
      PHG4SpacalPrototypeSubsystem *cemc;
      cemc = new PHG4SpacalPrototypeSubsystem("CEMC");
      cemc->SetActive();
      cemc->SuperDetector("CEMC");
      cemc->SetAbsorberActive();
      cemc->OverlapCheck(true);
//      cemc->Verbosity(2);
//      cemc->set_int_param("construction_verbose",2);
      cemc->UseCalibFiles(PHG4DetectorSubsystem::xml);
      cemc->SetCalibrationFileDir(string(getenv("CALIBRATIONROOT")) + string("/Prototype3/Geometry/") );
//      cemc->SetCalibrationFileDir("./test_geom/" );
      //  cemc->set_double_param("z_rotation_degree", 15); // rotation around CG
//      cemc->set_double_param("xpos", (116.77 + 137.0)*.5 - 26.5 - 10.2); // location in cm of EMCal CG. Updated with final positioning of EMCal
//      cemc->set_double_param("ypos", 4); // put it some where in UIUC blocks
//      cemc->set_double_param("zpos", 4); // put it some where in UIUC blocks
      g4Reco->registerSubsystem(cemc);
    }
  //----------------------------------------
  // HCal G4
  //----------------------------------------
  if (ihcal_on)
    {
      PHG4Prototype2InnerHcalSubsystem *innerhcal = new PHG4Prototype2InnerHcalSubsystem("HCalIn");
      innerhcal->set_int_param("hi_eta",1);
      innerhcal->set_double_param("place_x",add_place_x);
      innerhcal->set_double_param("place_z",144);
      innerhcal->SetActive();
      innerhcal->SetAbsorberActive();
      innerhcal->SetAbsorberTruth(1);
      innerhcal->OverlapCheck(true);
      innerhcal->SuperDetector("HCALIN");
      g4Reco->registerSubsystem(innerhcal);
    }
  if (ohcal_on)
    {
      PHG4Prototype2OuterHcalSubsystem *outerhcal = new PHG4Prototype2OuterHcalSubsystem("HCalOut");
      outerhcal->set_int_param("hi_eta",1);
      outerhcal->set_double_param("place_x",add_place_x);
      outerhcal->set_double_param("place_z",229.5);
      outerhcal->SetActive();
      outerhcal->SetAbsorberActive();
      outerhcal->SetAbsorberTruth(1);
      outerhcal->OverlapCheck(true);
      outerhcal->SuperDetector("HCALOUT");
      g4Reco->registerSubsystem(outerhcal);
    }
  if (cryo_on)
    {
      double place_z = 175.;
      // Cryostat from engineering drawing
      PHG4BlockSubsystem *cryo1 = new PHG4BlockSubsystem("cryo1",1);
      cryo1->set_double_param("size_x",0.95);
      cryo1->set_double_param("size_y",60.96);
      cryo1->set_double_param("size_z",60.96);
      cryo1->set_double_param("place_x",141.96+0.95/2.+add_place_x);
      cryo1->set_double_param("place_z",place_z);
      cryo1->set_string_param("material","G4_Al");
      cryo1->SetActive(); // it is an active volume - save G4Hits
      cryo1->SuperDetector("CRYO");
      g4Reco->registerSubsystem(cryo1);

      PHG4BlockSubsystem *cryo2 = new PHG4BlockSubsystem("cryo2",2);
      cryo2->set_double_param("size_x",8.89);
      cryo2->set_double_param("size_y",60.96);
      cryo2->set_double_param("size_z",60.96);
      cryo2->set_double_param("place_x",150.72+8.89/2.+add_place_x);
      cryo2->set_double_param("place_z",place_z);
      cryo2->set_string_param("material","G4_Al");
      cryo2->SetActive(); // it is an active volume - save G4Hits
      cryo2->SuperDetector("CRYO");
      g4Reco->registerSubsystem(cryo2);

      PHG4BlockSubsystem *cryo3 = new PHG4BlockSubsystem("cryo3",3);
      cryo3->set_double_param("size_x",2.54);
      cryo3->set_double_param("size_y",60.96);
      cryo3->set_double_param("size_z",60.96);
      cryo3->set_double_param("place_x",173.93+2.54/2.+add_place_x);
      cryo3->set_double_param("place_z",place_z);
      cryo3->set_string_param("material","G4_Al");
      cryo3->SetActive(); // it is an active volume - save G4Hits
      cryo3->SuperDetector("CRYO");
      g4Reco->registerSubsystem(cryo3);
    }
  if (bh_on)
    { 
      // BLACKHOLE, box surrounding the prototype to check for leakage
      PHG4BlockSubsystem *bh[5];
      // surrounding outer hcal
      // top
      bh[0] = new PHG4BlockSubsystem("bh1",1);
      bh[0]->set_double_param("size_x",270.);
      bh[0]->set_double_param("size_y",0.01);
      bh[0]->set_double_param("size_z",165.);
      bh[0]->set_double_param("place_x",270./2.);
      bh[0]->set_double_param("place_y",125./2.);
      // bottom
      bh[1] = new PHG4BlockSubsystem("bh2",2);
      bh[1]->set_double_param("size_x",270.);
      bh[1]->set_double_param("size_y",0.01);
      bh[1]->set_double_param("size_z",165.);
      bh[1]->set_double_param("place_x",270./2.);
      bh[1]->set_double_param("place_y",-125./2.);
      // right side
      bh[2] = new PHG4BlockSubsystem("bh3",3);
      bh[2]->set_double_param("size_x",200.);
      bh[2]->set_double_param("size_y",125.);
      bh[2]->set_double_param("size_z",0.01);
      bh[2]->set_double_param("place_x",200./2.);
      bh[2]->set_double_param("place_z",165./2.);
      // left side
      bh[3] = new PHG4BlockSubsystem("bh4",4);
      bh[3]->set_double_param("size_x",270.);
      bh[3]->set_double_param("size_y",125.);
      bh[3]->set_double_param("size_z",0.01);
      bh[3]->set_double_param("place_x",270./2.);
      bh[3]->set_double_param("place_z",-165./2.);
      // back
      bh[4] = new PHG4BlockSubsystem("bh5",5);
      bh[4]->set_double_param("size_x",0.01);
      bh[4]->set_double_param("size_y",125.);
      bh[4]->set_double_param("size_z",165.);
      bh[4]->set_double_param("place_x",270.);
      for (int i=0; i<5; i++)
	{
	  bh[i]->BlackHole();
	  bh[i]->SetActive();
	  bh[i]->SuperDetector("BlackHole");
	  bh[i]->OverlapCheck(true);
	  g4Reco->registerSubsystem(bh[i]);
	}
    }
  PHG4TruthSubsystem *truth = new PHG4TruthSubsystem();
  g4Reco->registerSubsystem(truth);

  se->registerSubsystem( g4Reco );
  //----------------------------------------
  // EMCal digitization
  //----------------------------------------
  if (cemc_cell)
    {
      PHG4FullProjSpacalCellReco *cemc_cells = new PHG4FullProjSpacalCellReco("CEMCCYLCELLRECO");
      cemc_cells->Detector("CEMC");
      cemc_cells->set_timing_window(0.,60.);
      cemc_cells->get_light_collection_model().load_data_file(string(getenv("CALIBRATIONROOT")) + string("/CEMC/LightCollection/Prototype2Module.xml"),"data_grid_light_guide_efficiency","data_grid_fiber_trans");

      se->registerSubsystem(cemc_cells);
    }
  if (cemc_twr)
    {
      RawTowerBuilder *TowerBuilder = new RawTowerBuilder("EmcRawTowerBuilder");
      TowerBuilder->Detector("CEMC");
      TowerBuilder->set_sim_tower_node_prefix("SIM");
      se->registerSubsystem(TowerBuilder);
    }
  const double sampling_fraction = 0.0190134; //  +/-   0.000224984  from 0 Degree indenting 32 GeV electron showers
  const double photoelectron_per_GeV = 500; //500 photon per total GeV deposition
  const double ADC_per_photoelectron_HG = 3.8; // From Sean Stoll, Mar 29
  const double ADC_per_photoelectron_LG = 0.24; // From Sean Stoll, Mar 29

  // low gains
  if (cemc_digi)
    {
      RawTowerDigitizer *TowerDigitizer = new RawTowerDigitizer("EmcRawTowerDigitizerLG");
      TowerDigitizer->Detector("CEMC");
      TowerDigitizer->set_raw_tower_node_prefix("RAW_LG");
      TowerDigitizer->set_digi_algorithm(RawTowerDigitizer::kSimple_photon_digitalization);
      TowerDigitizer->set_pedstal_central_ADC(0);
      TowerDigitizer->set_pedstal_width_ADC(1); // From Jin's guess. No EMCal High Gain data yet! TODO: update
      TowerDigitizer->set_photonelec_ADC(1. / ADC_per_photoelectron_LG);
      TowerDigitizer->set_photonelec_yield_visible_GeV(photoelectron_per_GeV / sampling_fraction);
      TowerDigitizer->set_zero_suppression_ADC(-1000); // no-zero suppression
      se->registerSubsystem(TowerDigitizer);
      // high gains
      TowerDigitizer = new RawTowerDigitizer("EmcRawTowerDigitizerHG");
      TowerDigitizer->Detector("CEMC");
      TowerDigitizer->set_raw_tower_node_prefix("RAW_HG");
      TowerDigitizer->set_digi_algorithm(
					 RawTowerDigitizer::kSimple_photon_digitalization);
      TowerDigitizer->set_pedstal_central_ADC(0);
      TowerDigitizer->set_pedstal_width_ADC(15); // From John Haggerty, Mar 29
      TowerDigitizer->set_photonelec_ADC(1. / ADC_per_photoelectron_HG);
      TowerDigitizer->set_photonelec_yield_visible_GeV(photoelectron_per_GeV / sampling_fraction);
      TowerDigitizer->set_zero_suppression_ADC(-1000); // no-zero suppression
      se->registerSubsystem(TowerDigitizer);
    }
  if (cemc_twrcal)
    {
      RawTowerCalibration *TowerCalibration = new RawTowerCalibration("EmcRawTowerCalibrationLG");
      TowerCalibration->Detector("CEMC");
      TowerCalibration->set_raw_tower_node_prefix("RAW_LG");
      TowerCalibration->set_calib_tower_node_prefix("CALIB_LG");
      TowerCalibration->set_calib_algorithm(RawTowerCalibration::kSimple_linear_calibration);
      TowerCalibration->set_calib_const_GeV_ADC(1. / ADC_per_photoelectron_LG / photoelectron_per_GeV);
      TowerCalibration->set_pedstal_ADC(0);
      TowerCalibration->set_zero_suppression_GeV(-1); // no-zero suppression
      se->registerSubsystem(TowerCalibration);


      TowerCalibration = new RawTowerCalibration("EmcRawTowerCalibrationHG");
      TowerCalibration->Detector("CEMC");
      TowerCalibration->set_raw_tower_node_prefix("RAW_HG");
      TowerCalibration->set_calib_tower_node_prefix("CALIB_HG");
      TowerCalibration->set_calib_algorithm(
					    RawTowerCalibration::kSimple_linear_calibration);
      TowerCalibration->set_calib_const_GeV_ADC(1. / ADC_per_photoelectron_HG / photoelectron_per_GeV);
      TowerCalibration->set_pedstal_ADC(0);
      TowerCalibration->set_zero_suppression_GeV(-1); // no-zero suppression
      se->registerSubsystem(TowerCalibration);
    }

  //----------------------------------------
  // HCal towering
  //----------------------------------------
  if (ihcal_cell)
    {
      PHG4Prototype2HcalCellReco *hccell = new PHG4Prototype2HcalCellReco("HCALinCellReco");
      hccell->Detector("HCALIN");
      se->registerSubsystem(hccell);
    }
  if (ihcal_twr)
    {
      Prototype2RawTowerBuilder *hcaltwr = new Prototype2RawTowerBuilder("HCALinRawTowerBuilder");
      hcaltwr->Detector("HCALIN");
      hcaltwr->set_sim_tower_node_prefix("SIM");
      se->registerSubsystem(hcaltwr);
    }


  if (ohcal_cell)
    {
      hccell = new PHG4Prototype2HcalCellReco("HCALoutCellReco");
      hccell->Detector("HCALOUT");
      se->registerSubsystem(hccell);
    }
  if (ohcal_twr)
    {
      hcaltwr = new Prototype2RawTowerBuilder("HCALoutRawTowerBuilder");
      hcaltwr->Detector("HCALOUT");
      hcaltwr->set_sim_tower_node_prefix("SIM");
      se->registerSubsystem(hcaltwr);
    }

  //----------------------------------------
  // HCal digitization
  //----------------------------------------
  //  From: Abhisek Sen [mailto:[email protected]]
  //  Sent: Tuesday, April 19, 2016 10:55 PM
  //  To: Huang, Jin <*****@*****.**>; Haggerty, John <*****@*****.**>

  //  HCALIN:
  //     1/5 pixel / HG ADC channel
  //     32/5 pixel / LG ADC channel
  //     0.4 MeV/ LG ADC
  //     0.4/32 MeV/ HG ADC

  //  HCALOUT:
  //     1/5 pixel / HG ADC channel
  //     16/5 pixel / LG ADC channel
  //     0.2 MeV/ LG ADC
  //     0.2/16 MeV/ HG ADC
  RawTowerDigitizer *TowerDigitizer = NULL;
  if (ihcal_digi)
    {
      TowerDigitizer = new RawTowerDigitizer("HCALinTowerDigitizerLG");
      TowerDigitizer->Detector("HCALIN");
      TowerDigitizer->set_raw_tower_node_prefix("RAW_LG");
      TowerDigitizer->set_digi_algorithm(RawTowerDigitizer::kSimple_photon_digitalization);
      TowerDigitizer->set_pedstal_central_ADC(0);
      TowerDigitizer->set_pedstal_width_ADC(1); // From Jin's guess. No EMCal High Gain data yet! TODO: update
      TowerDigitizer->set_photonelec_ADC(32. / 5.);
      TowerDigitizer->set_photonelec_yield_visible_GeV(32. / 5 / (0.4e-3));
      TowerDigitizer->set_zero_suppression_ADC(-1000); // no-zero suppression
      se->registerSubsystem(TowerDigitizer);

      TowerDigitizer = new RawTowerDigitizer("HCALinTowerDigitizerHG");
      TowerDigitizer->Detector("HCALIN");
      TowerDigitizer->set_raw_tower_node_prefix("RAW_HG");
      TowerDigitizer->set_digi_algorithm(RawTowerDigitizer::kSimple_photon_digitalization);
      TowerDigitizer->set_pedstal_central_ADC(0);
      TowerDigitizer->set_pedstal_width_ADC(1); // From Jin's guess. No EMCal High Gain data yet! TODO: update
      TowerDigitizer->set_photonelec_ADC(1. / 5.);
      TowerDigitizer->set_photonelec_yield_visible_GeV(1. / 5 / (0.4e-3 / 32));
      TowerDigitizer->set_zero_suppression_ADC(-1000); // no-zero suppression
      se->registerSubsystem(TowerDigitizer);
    }
  if (ohcal_digi)
    {
      TowerDigitizer = new RawTowerDigitizer("HCALoutTowerDigitizerLG");
      TowerDigitizer->Detector("HCALOUT");
      TowerDigitizer->set_raw_tower_node_prefix("RAW_LG");
      TowerDigitizer->set_digi_algorithm(RawTowerDigitizer::kSimple_photon_digitalization);
      TowerDigitizer->set_pedstal_central_ADC(0);
      TowerDigitizer->set_pedstal_width_ADC(1); // From Jin's guess. No EMCal High Gain data yet! TODO: update
      TowerDigitizer->set_photonelec_ADC(16. / 5.);
      TowerDigitizer->set_photonelec_yield_visible_GeV(16. / 5 / (0.2e-3));
      TowerDigitizer->set_zero_suppression_ADC(-1000); // no-zero suppression
      se->registerSubsystem(TowerDigitizer);

      TowerDigitizer = new RawTowerDigitizer("HCALoutTowerDigitizerHG");
      TowerDigitizer->Detector("HCALOUT");
      TowerDigitizer->set_raw_tower_node_prefix("RAW_HG");
      TowerDigitizer->set_digi_algorithm(RawTowerDigitizer::kSimple_photon_digitalization);
      TowerDigitizer->set_pedstal_central_ADC(0);
      TowerDigitizer->set_pedstal_width_ADC(1); // From Jin's guess. No EMCal High Gain data yet! TODO: update
      TowerDigitizer->set_photonelec_ADC(1. / 5.);
      TowerDigitizer->set_photonelec_yield_visible_GeV(1. / 5 / (0.2e-3 / 16));
      TowerDigitizer->set_zero_suppression_ADC(-1000); // no-zero suppression
      se->registerSubsystem(TowerDigitizer);
    }
  //----------------------------------------
  // HCal calibration
  //----------------------------------------
  // 32 GeV Pi+ scan
  const double visible_sample_fraction_HCALIN = 7.19505e-02 ; // 1.34152e-02
  const double visible_sample_fraction_HCALOUT = 0.0313466 ; //  +/-   0.0067744
  RawTowerCalibration *TowerCalibration = NULL;
  if (ihcal_twrcal)
    {
      TowerCalibration = new RawTowerCalibration("HCALinRawTowerCalibrationLG");
      TowerCalibration->Detector("HCALIN");
      TowerCalibration->set_raw_tower_node_prefix("RAW_LG");
      TowerCalibration->set_calib_tower_node_prefix("CALIB_LG");
      TowerCalibration->set_calib_algorithm(RawTowerCalibration::kSimple_linear_calibration);
      TowerCalibration->set_calib_const_GeV_ADC(0.4e-3 / visible_sample_fraction_HCALIN);
      TowerCalibration->set_pedstal_ADC(0);
      TowerCalibration->set_zero_suppression_GeV(-1); // no-zero suppression
      se->registerSubsystem(TowerCalibration);

      TowerCalibration = new RawTowerCalibration("HCALinRawTowerCalibrationHG");
      TowerCalibration->Detector("HCALIN");
      TowerCalibration->set_raw_tower_node_prefix("RAW_HG");
      TowerCalibration->set_calib_tower_node_prefix("CALIB_HG");
      TowerCalibration->set_calib_algorithm(RawTowerCalibration::kSimple_linear_calibration);
      TowerCalibration->set_calib_const_GeV_ADC(0.4e-3 / 32 / visible_sample_fraction_HCALIN);
      TowerCalibration->set_pedstal_ADC(0);
      TowerCalibration->set_zero_suppression_GeV(-1); // no-zero suppression
      se->registerSubsystem(TowerCalibration);
    }
  if (ohcal_twrcal)
    {
      TowerCalibration = new RawTowerCalibration("HCALoutRawTowerCalibrationLG");
      TowerCalibration->Detector("HCALOUT");
      TowerCalibration->set_raw_tower_node_prefix("RAW_LG");
      TowerCalibration->set_calib_tower_node_prefix("CALIB_LG");
      TowerCalibration->set_calib_algorithm(RawTowerCalibration::kSimple_linear_calibration);
      TowerCalibration->set_calib_const_GeV_ADC(0.2e-3 / visible_sample_fraction_HCALOUT);
      TowerCalibration->set_pedstal_ADC(0);
      TowerCalibration->set_zero_suppression_GeV(-1); // no-zero suppression
      se->registerSubsystem(TowerCalibration);

      TowerCalibration = new RawTowerCalibration("HCALoutRawTowerCalibrationHG");
      TowerCalibration->Detector("HCALOUT");
      TowerCalibration->set_raw_tower_node_prefix("RAW_HG");
      TowerCalibration->set_calib_tower_node_prefix("CALIB_HG");
      TowerCalibration->set_calib_algorithm(RawTowerCalibration::kSimple_linear_calibration);
      TowerCalibration->set_calib_const_GeV_ADC(0.2e-3 / 16 / visible_sample_fraction_HCALOUT);
      TowerCalibration->set_pedstal_ADC(0);
      TowerCalibration->set_zero_suppression_GeV(-1); // no-zero suppression
      se->registerSubsystem(TowerCalibration);
    }
  //----------------------
  // QA Histograms
  //----------------------
  if (cemc_on)
    {
      se->registerSubsystem(new QAG4SimulationCalorimeter("CEMC",QAG4SimulationCalorimeter::kProcessG4Hit));
    }
  if (ihcal_on)
    {
      // TODO: disable QA for HCal right now as there is a hit->particle truth association error at the moment
      // se->registerSubsystem(new QAG4SimulationCalorimeter("HCALIN",QAG4SimulationCalorimeter::kProcessG4Hit));
    }
  if (ohcal_on)
    {
      // se->registerSubsystem(new QAG4SimulationCalorimeter("HCALOUT",QAG4SimulationCalorimeter::kProcessG4Hit));
    }
  //----------------------
  // G4HitNtuple
  //----------------------
  if (hit_ntuple)
    {
      G4HitNtuple *hit = new G4HitNtuple("G4HitNtuple","g4hitntuple.root");
      hit->AddNode("HCALIN", 0);
      hit->AddNode("HCALOUT", 1);
      hit->AddNode("CRYO", 2);
      hit->AddNode("BlackHole", 3);
      hit->AddNode("ABSORBER_HCALIN", 10);
      hit->AddNode("ABSORBER_HCALOUT", 11);
      se->registerSubsystem(hit);
    }
  // G4ScintillatorSlatTTree *scintcell = new G4ScintillatorSlatTTree("inslat");
  // scintcell->Detector("HCALIN");
  // se->registerSubsystem(scintcell);

  // scintcell = new G4ScintillatorSlatTTree("outslat");
  // scintcell->Detector("HCALOUT");
  // se->registerSubsystem(scintcell);


  //----------------------
  // save a comprehensive  evaluation file
  //----------------------
  if (dstreader)
    {
      PHG4DSTReader* ana = new PHG4DSTReader(string("DSTReader.root"));
      ana->set_save_particle(true);
      ana->set_load_all_particle(false);
      ana->set_load_active_particle(false);
      ana->set_save_vertex(true);
      ana->set_tower_zero_sup(-1000); // no zero suppression

      //  ana->AddNode("CEMC");
      //  if (absorberactive)
      //    {
      //      ana->AddNode("ABSORBER_CEMC");
      //    }

      if (cemc_twr)
        ana->AddTower("SIM_CEMC");
      if (cemc_digi)
        ana->AddTower("RAW_LG_CEMC");
      if (cemc_twrcal)
        ana->AddTower("CALIB_LG_CEMC"); // Low gain CEMC
      if (cemc_digi)
        ana->AddTower("RAW_HG_CEMC");
      if (cemc_twrcal)
        ana->AddTower("CALIB_HG_CEMC"); // High gain CEMC

      if (ohcal_twr)
        ana->AddTower("SIM_HCALOUT");
      if (ihcal_twr)
        ana->AddTower("SIM_HCALIN");

      if (ihcal_digi)
        ana->AddTower("RAW_LG_HCALIN");
      if (ihcal_digi)
        ana->AddTower("RAW_HG_HCALIN");
      if (ohcal_digi)
        ana->AddTower("RAW_LG_HCALOUT");
      if (ohcal_digi)
        ana->AddTower("RAW_HG_HCALOUT");

      if (ihcal_twrcal)
        ana->AddTower("CALIB_LG_HCALIN");
      if (ihcal_twrcal)
        ana->AddTower("CALIB_HG_HCALIN");
      if (ohcal_twrcal)
        ana->AddTower("CALIB_LG_HCALOUT");
      if (ohcal_twrcal)
        ana->AddTower("CALIB_HG_HCALOUT");

      if (bh_on)
        ana->AddNode("BlackHole"); // add a G4Hit node

      se->registerSubsystem(ana);
    }

  // Fun4AllDstOutputManager *out = new Fun4AllDstOutputManager("DSTOUT","/phenix/scratch/pinkenbu/G4Prototype2Hcalin.root");
  // out->AddNode("G4RootScintillatorSlat_HCALIN");
  // se->registerOutputManager(out);

  // out = new Fun4AllDstOutputManager("DSTHCOUT","/phenix/scratch/pinkenbu/G4Prototype2Hcalout.root");
  // out->AddNode("G4RootScintillatorSlat_HCALOUT");
  // se->registerOutputManager(out);

  if (dstoutput)
    {
      Fun4AllDstOutputManager *out = new Fun4AllDstOutputManager("DSTOUT","G4Prototype3New.root");
      se->registerOutputManager(out);
    }

  Fun4AllInputManager *in = new Fun4AllDummyInputManager( "JADE");
  se->registerInputManager( in );
  if (nEvents <= 0)
    {
      return 0;
    }
  se->run(nEvents);

  se->End();

  QAHistManagerDef::saveQARootFile("G4Prototype2_qa.root");


  //   std::cout << "All done" << std::endl;
  delete se;
  //   return 0;
  gSystem->Exit(0);

}
//! ePHENIX simulation loading script
//! \param[in] nEvents Number of events to run. If nEvents=1, then a event display will be shown
//! \param[in] outputFile output for G4DSTReader
//! \param[in] inputFile HepMC input files, not activated by default
int
Fun4All_G4_ePHENIX( //
//        int nEvents = 0, //
    //    int nEvents = 1, //
    int nEvents = 2, //
//    int nEvents = 100000, //
    const char * outputFile = "G4ePHENIX.root", //
    const char * inputFile = "MyPythia.dat" //
    )
{
  //---------------
  // Load libraries
  //---------------

  const bool readhepmc = false; // read HepMC files
  const int absorberactive = 1; // set to 1 to make all absorbers active volumes
  const bool verbosity = false; // very slow but very detailed logs
//  const bool verbosity = true; // very slow but very detailed logs

  gSystem->Load("libg4testbench.so");
  gSystem->Load("libfun4all.so");
  gSystem->Load("libcemc.so");
  gSystem->Load("libg4eval.so");

  gROOT->LoadMacro("G4Setup_ePHENIX.C");

  G4Init(); // initialize layer numbers for barrel

  //---------------
  // Fun4All server
  //---------------

  Fun4AllServer *se = Fun4AllServer::instance();
  se->Verbosity(0);

  //-----------------
  // Event generation
  //-----------------
  if (readhepmc)
    {
      // this module is needed to read the HepMC records into our G4 sims
      // but only if you read HepMC input files
      HepMCNodeReader *hr = new HepMCNodeReader();
      se->registerSubsystem(hr);
    }
  else
    {
      // The PHG4ParticleGun runs the same particle(s) in
      // every event

      PHG4ParticleGun *gun = new PHG4ParticleGun();
//          gun->set_name("geantino+");
//      gun->set_name("chargedgeantino");
      gun->set_name("mu-");
//      gun->set_name("pi-"); // e,pi,mu,p,gamma
      //    gun->set_vtx(0,12.09,200);
      gun->set_vtx(0, 0, 0);
//        gun->set_mom(0, 0, 10);
      gun->set_mom(1.12641e-16, 1.83962, 13.6021);
//      se->registerSubsystem(gun);

      PHG4ParticleGenerator *gen = new PHG4ParticleGenerator();

      //      gen->set_seed(TRandom3(0).GetSeed());
      gen->set_seed(1234);
//      gen->set_name("geantino");
      gen->set_name("mu-");
//      gun->set_name("pi-"); // e,pi,mu,p,gamma
      gen->set_vtx(0, 0, 0);
      gen->set_z_range(0, 0);
//      gen->set_eta_range(3.5, 3.5);
      gen->set_eta_range(-4, 4);
      gen->set_phi_range(TMath::Pi() / 2, TMath::Pi() / 2);
      gen->set_mom_range(1.0, 50.0);
      gen->Verbosity(1);
//      se->registerSubsystem(gen);
//
      //! high Q2 250x10 GeV pythia file from Kieran
      ReadEICFiles *eic = new ReadEICFiles();
      const char *infile =
          "/direct/phenix+sim02/phnxreco/ePHENIX/jinhuang/display/pythia.ep.250x010.10000000events.seed679586890.root";
      eic->OpenInputFile(infile);
      eic->SetFirstEntry(565);
      se->registerSubsystem(eic);

    }
  //---------------------
  // Detector description from loaded macro
  //---------------------

  G4Setup(absorberactive, -1);
//  G4Setup_Sandbox(absorberactive, -1);

//  MaterialScan();
  //----------------------
  // Simulation evaluation
  //----------------------

//  SubsysReco* eval = new PHG4Evaluator("PHG4EVALUATOR","g4eval.root");
  //eval->Verbosity(0);
  //se->registerSubsystem( eval );

  //SubsysReco* eval = new PHG4CEMCEvaluator("PHG4CEMCEVALUATOR","out/g4eval.root");
  //eval->Verbosity(1);
  //se->registerSubsystem( eval );

  //     HitNtuples *hits = new HitNtuples();
  //        hits->AddNode("FEMCABS",0);
  //        hits->AddNode("FEMC",3);
  //        hits->AddNode("FPRESHOWER",1);
  //        hits->AddNode("GEM",2);
  //        hits->AddNode("GEMLIDFRONT",4);
  //        hits->AddNode("GEMLIDBACK",5);
  //    se->registerSubsystem(hits);

  //----------------------
  // Save selected nodes to root file
  //----------------------
    {
      // require offline/analysis/g4analysis_fsphenix

    PHG4DSTReader* ana = new PHG4DSTReader(outputFile);
      if (nEvents > 0 && nEvents < 3)
        ana->Verbosity(2);
      ana->AddNode("GEMSTATION0");
      ana->AddNode("GEMSTATION1");
      ana->AddNode("GEMSTATION2");
      ana->AddNode("GEMSTATION3");
      ana->AddNode("GEMSTATION4");
//      ana->AddNode("TestDetector_0");
      se->registerSubsystem(ana);

    }

  //--------------
  // IO management
  //--------------

  if (readhepmc)
    {
      Fun4AllInputManager *in = new Fun4AllHepMCInputManager("DSTIN");
      se->registerInputManager(in);
      se->fileopen(in->Name(), inputFile);
    }
  else
    {
      // for single particle generators we just need something which drives
      // the event loop, the Dummy Input Mgr does just that
      Fun4AllInputManager *in = new Fun4AllDummyInputManager("JADE");
      se->registerInputManager(in);
    }

  // File Managers
  bool save_dst = false;
  if (save_dst)
    {
      Fun4AllDstOutputManager *dstManager = new Fun4AllDstOutputManager(
          "DSTOUT", "DST.root");
      //FVTX nodes
      dstManager->AddNode("PHG4INEVENT");
      dstManager->AddNode("G4TruthInfo");

      se->registerOutputManager(dstManager);
    }

  //-----------------
  // Event processing
  //-----------------

  if (nEvents == 1)
    {
      PHG4Reco *g4 = (PHG4Reco *) se->getSubsysReco("PHG4RECO");
      g4->ApplyCommand("/control/execute eic.mac");
//      g4->StartGui();
      se->run(1);

      se->End();
      std::cout << "All done" << std::endl;
    }
  else
    {
      if (verbosity)
        {
          se->Verbosity(3);
          PHG4Reco *g4 = (PHG4Reco *) se->getSubsysReco("PHG4RECO");
          g4->Verbosity(3);
          g4->ApplyCommand("/control/verbose 5");
          g4->ApplyCommand("/run/verbose  5");
          g4->ApplyCommand("/tracking/verbose 5");
        }

      se->run(nEvents);

      se->End();
      std::cout << "All done" << std::endl;
      delete se;
      gSystem->Exit(0);
    }

  //   //-----
  //   // Exit
  //   //-----

  return 0;
}
int Fun4All_G4_sPHENIX_photonjet(
    const int nEvents = 5,
    const char *inputFile = "hepmc_pythia.dat",
    const char *outputFile = "G4sPHENIX.root",
    const char *embed_input_file = "/sphenix/data/data02/review_2017-08-02/sHijing/fm_0-4.list")
{
  // Set the number of TPC layer
  const int n_TPC_layers = 40;  // use 60 for backward compatibility only

  //===============
  // Input options
  //===============

  // Either:
  // read previously generated g4-hits files, in this case it opens a DST and skips
  // the simulations step completely. The G4Setup macro is only loaded to get information
  // about the number of layers used for the cell reco code
  //
  // In case reading production output, please double check your G4Setup_sPHENIX.C and G4_*.C consistent with those in the production macro folder
  // E.g. /sphenix/sim//sim01/production/2016-07-21/single_particle/spacal2d/
  const bool readhits = false;
  // Or:
  // read files in HepMC format (typically output from event generators like hijing or pythia)
  const bool readhepmc = true;  // read HepMC files
  // Or:
  // Use pythia
  const bool runpythia8 = false;
  const bool runpythia6 = false;
  //
  // **** And ****
  // Further choose to embed newly simulated events to a previous simulation. Not compatible with `readhits = true`
  // In case embedding into a production output, please double check your G4Setup_sPHENIX.C and G4_*.C consistent with those in the production macro folder
  // E.g. /sphenix/data/data02/review_2017-08-02/
  const bool do_embedding = false;

  // Besides the above flags. One can further choose to further put in following particles in Geant4 simulation
  // Use multi-particle generator (PHG4SimpleEventGenerator), see the code block below to choose particle species and kinematics
  const bool particles = false && !readhits;
  // or gun/ very simple single particle gun generator
  const bool usegun = false && !readhits;
  // Throw single Upsilons, may be embedded in Hijing by setting readhepmc flag also  (note, careful to set Z vertex equal to Hijing events)
  const bool upsilons = false && !readhits;
  // Event pile up simulation with collision rate in Hz MB collisions.
  // Note please follow up the macro to verify the settings for beam parameters
  const double pileup_collision_rate = 0;  // 100e3 for 100kHz nominal AuAu collision rate.

  //======================
  // What to run
  //======================

  bool do_bbc = true;

  bool do_pipe = true;

  bool do_svtx = true;
  bool do_svtx_cell = do_svtx && true;
  bool do_svtx_track = do_svtx_cell && true;
  bool do_svtx_eval = do_svtx_track && false;

  bool do_pstof = false;

  bool do_cemc = true;
  bool do_cemc_cell = do_cemc && true;
  bool do_cemc_twr = do_cemc_cell && true;
  bool do_cemc_cluster = do_cemc_twr && true;
  bool do_cemc_eval = do_cemc_cluster && false;

  bool do_hcalin = true;
  bool do_hcalin_cell = do_hcalin && true;
  bool do_hcalin_twr = do_hcalin_cell && true;
  bool do_hcalin_cluster = do_hcalin_twr && true;
  bool do_hcalin_eval = do_hcalin_cluster && false;

  bool do_magnet = true;

  bool do_hcalout = true;
  bool do_hcalout_cell = do_hcalout && true;
  bool do_hcalout_twr = do_hcalout_cell && true;
  bool do_hcalout_cluster = do_hcalout_twr && true;
  bool do_hcalout_eval = do_hcalout_cluster && false;

  //! forward flux return plug door. Out of acceptance and off by default.
  bool do_plugdoor = false;

  bool do_global = true;
  bool do_global_fastsim = true;

  bool do_calotrigger = true && do_cemc_twr && do_hcalin_twr && do_hcalout_twr;

  bool do_jet_reco = true;
  bool do_jet_eval = do_jet_reco && true;

  // HI Jet Reco for p+Au / Au+Au collisions (default is false for
  // single particle / p+p-only simulations, or for p+Au / Au+Au
  // simulations which don't particularly care about jets)
  bool do_HIjetreco = false && do_cemc_twr && do_hcalin_twr && do_hcalout_twr;

  bool do_dst_compress = false;

  //Option to convert DST to human command readable TTree for quick poke around the outputs
  bool do_DSTReader = false;
  //---------------
  // Load libraries
  //---------------

  gSystem->Load("libfun4all.so");
  gSystem->Load("libg4detectors.so");
  gSystem->Load("libphhepmc.so");
  gSystem->Load("libg4testbench.so");
  gSystem->Load("libg4hough.so");
  gSystem->Load("libg4eval.so");

  // establish the geometry and reconstruction setup
  gROOT->LoadMacro("G4Setup_sPHENIX.C");
  G4Init(do_svtx, do_pstof, do_cemc, do_hcalin, do_magnet, do_hcalout, do_pipe, do_plugdoor, n_TPC_layers);

  int absorberactive = 1;  // set to 1 to make all absorbers active volumes
  //  const string magfield = "1.5"; // if like float -> solenoidal field in T, if string use as fieldmap name (including path)
  const string magfield = "/phenix/upgrades/decadal/fieldmaps/sPHENIX.2d.root";  // if like float -> solenoidal field in T, if string use as fieldmap name (including path)
  const float magfield_rescale = -1.4 / 1.5;                                     // scale the map to a 1.4 T field

  //---------------
  // Fun4All server
  //---------------

  Fun4AllServer *se = Fun4AllServer::instance();
  se->Verbosity(0);
  // just if we set some flags somewhere in this macro
  recoConsts *rc = recoConsts::instance();
  // By default every random number generator uses
  // PHRandomSeed() which reads /dev/urandom to get its seed
  // if the RANDOMSEED flag is set its value is taken as seed
  // You ca neither set this to a random value using PHRandomSeed()
  // which will make all seeds identical (not sure what the point of
  // this would be:
  //  rc->set_IntFlag("RANDOMSEED",PHRandomSeed());
  // or set it to a fixed value so you can debug your code
  //  rc->set_IntFlag("RANDOMSEED", 12345);

  //-----------------
  // Event generation
  //-----------------

  if (readhits)
  {
    // Get the hits from a file
    // The input manager is declared later

    if (do_embedding)
    {
      cout << "Do not support read hits and embed background at the same time." << endl;
      exit(1);
    }
  }
  else
  {
    // running Geant4 stage. First load event generators.

    if (readhepmc)
    {
      // place holder. Additional action is performed in later stage at the input manager level
      HepMCNodeReader *hr = new HepMCNodeReader();
      se->registerSubsystem(hr);
    }

    if (runpythia8)
    {
      gSystem->Load("libPHPythia8.so");

      PHPythia8 *pythia8 = new PHPythia8();
      // see coresoftware/generators/PHPythia8 for example config
      pythia8->set_config_file("phpythia8.cfg");

      
      PHPy8ParticleTrigger *ptrig = new PHPy8ParticleTrigger();
      ptrig->AddParticles(22);
      ptrig->SetPtLow(10);
      ptrig->SetEtaHigh(1);
      ptrig->SetEtaLow(-1);
      ptrig->PrintConfig();
      pythia8->register_trigger(ptrig);

      PHPy8JetTrigger *trig = new PHPy8JetTrigger();
      trig->SetEtaHighLow(-1,1);
      trig->SetMinJetPt(5);
      trig->SetJetR(0.4);
      pythia8->register_trigger(trig);
      
      if (readhepmc)
        pythia8->set_reuse_vertex(0);  // reuse vertex of subevent with embedding ID of 0
      // pythia8->set_vertex_distribution_width(0,0,10,0); // additional vertex smearing if needed, more vertex options available
      se->registerSubsystem(pythia8);
    }

    if (runpythia6)
    {
      gSystem->Load("libPHPythia6.so");

      PHPythia6 *pythia6 = new PHPythia6();
      pythia6->set_config_file("phpythia6.cfg");
      if (readhepmc)
        pythia6->set_reuse_vertex(0);  // reuse vertex of subevent with embedding ID of 0
      // pythia6->set_vertex_distribution_width(0,0,10,0); // additional vertex smearing if needed, more vertex options available
      se->registerSubsystem(pythia6);
    }

    // If "readhepMC" is also set, the particles will be embedded in Hijing events
    if (particles)
    {
      // toss low multiplicity dummy events
      PHG4SimpleEventGenerator *gen = new PHG4SimpleEventGenerator();
      gen->add_particles("pi-", 2);  // mu+,e+,proton,pi+,Upsilon
      //gen->add_particles("pi+",100); // 100 pion option
      if (readhepmc || do_embedding || runpythia8 || runpythia6)
      {
        gen->set_reuse_existing_vertex(true);
        gen->set_existing_vertex_offset_vector(0.0, 0.0, 0.0);
      }
      else
      {
        gen->set_vertex_distribution_function(PHG4SimpleEventGenerator::Uniform,
                                              PHG4SimpleEventGenerator::Uniform,
                                              PHG4SimpleEventGenerator::Uniform);
        gen->set_vertex_distribution_mean(0.0, 0.0, 0.0);
        gen->set_vertex_distribution_width(0.0, 0.0, 5.0);
      }
      gen->set_vertex_size_function(PHG4SimpleEventGenerator::Uniform);
      gen->set_vertex_size_parameters(0.0, 0.0);
      gen->set_eta_range(-1.0, 1.0);
      gen->set_phi_range(-1.0 * TMath::Pi(), 1.0 * TMath::Pi());
      //gen->set_pt_range(0.1, 50.0);
      gen->set_pt_range(0.1, 20.0);
      gen->Embed(2);
      gen->Verbosity(0);

      se->registerSubsystem(gen);
    }

    if (usegun)
    {
      PHG4ParticleGun *gun = new PHG4ParticleGun();
      //  gun->set_name("anti_proton");
      gun->set_name("geantino");
      gun->set_vtx(0, 0, 0);
      gun->set_mom(10, 0, 0.01);
      // gun->AddParticle("geantino",1.7776,-0.4335,0.);
      // gun->AddParticle("geantino",1.7709,-0.4598,0.);
      // gun->AddParticle("geantino",2.5621,0.60964,0.);
      // gun->AddParticle("geantino",1.8121,0.253,0.);
      //	  se->registerSubsystem(gun);
      PHG4ParticleGenerator *pgen = new PHG4ParticleGenerator();
      pgen->set_name("geantino");
      pgen->set_z_range(0, 0);
      pgen->set_eta_range(0.01, 0.01);
      pgen->set_mom_range(10, 10);
      pgen->set_phi_range(5.3 / 180. * TMath::Pi(), 5.7 / 180. * TMath::Pi());
      se->registerSubsystem(pgen);
    }

    // If "readhepMC" is also set, the Upsilons will be embedded in Hijing events, if 'particles" is set, the Upsilons will be embedded in whatever particles are thrown
    if (upsilons)
    {
      // run upsilons for momentum, dca performance, alone or embedded in Hijing

      PHG4ParticleGeneratorVectorMeson *vgen = new PHG4ParticleGeneratorVectorMeson();
      vgen->add_decay_particles("e+", "e-", 0);  // i = decay id
      // event vertex
      if (readhepmc || do_embedding || particles || runpythia8 || runpythia6)
      {
        vgen->set_reuse_existing_vertex(true);
      }
      else
      {
        vgen->set_vtx_zrange(-10.0, +10.0);
      }

      // Note: this rapidity range completely fills the acceptance of eta = +/- 1 unit
      vgen->set_rapidity_range(-1.0, +1.0);
      vgen->set_pt_range(0.0, 10.0);

      int istate = 1;

      if (istate == 1)
      {
        // Upsilon(1S)
        vgen->set_mass(9.46);
        vgen->set_width(54.02e-6);
      }
      else if (istate == 2)
      {
        // Upsilon(2S)
        vgen->set_mass(10.0233);
        vgen->set_width(31.98e-6);
      }
      else
      {
        // Upsilon(3S)
        vgen->set_mass(10.3552);
        vgen->set_width(20.32e-6);
      }

      vgen->Verbosity(0);
      vgen->Embed(3);
      se->registerSubsystem(vgen);

      cout << "Upsilon generator for istate = " << istate << " created and registered " << endl;
    }
  }
  
  if (!readhits)
  {
    //---------------------
    // Detector description
    //---------------------

    G4Setup(absorberactive, magfield, TPythia6Decayer::kAll,
            do_svtx, do_pstof, do_cemc, do_hcalin, do_magnet, do_hcalout, do_pipe,do_plugdoor, magfield_rescale);
  }

  //---------
  // BBC Reco
  //---------
 
  if (do_bbc)
  {
    gROOT->LoadMacro("G4_Bbc.C");
    BbcInit();
    Bbc_Reco();
  }
  //------------------
  // Detector Division
  //------------------

  if (do_svtx_cell) Svtx_Cells();

  if (do_cemc_cell) CEMC_Cells();

  if (do_hcalin_cell) HCALInner_Cells();

  if (do_hcalout_cell) HCALOuter_Cells();

  //-----------------------------
  // CEMC towering and clustering
  //-----------------------------
 
  if (do_cemc_twr) CEMC_Towers();
  if (do_cemc_cluster) CEMC_Clusters();

  //-----------------------------
  // HCAL towering and clustering
  //-----------------------------
  
  if (do_hcalin_twr) HCALInner_Towers();
  if (do_hcalin_cluster) HCALInner_Clusters();

  if (do_hcalout_twr) HCALOuter_Towers();
  if (do_hcalout_cluster) HCALOuter_Clusters();

  if (do_dst_compress) ShowerCompress();

  //--------------
  // SVTX tracking
  //--------------
  
  if (do_svtx_track) Svtx_Reco();

  //-----------------
  // Global Vertexing
  //-----------------
  
  if (do_global)
  {
    gROOT->LoadMacro("G4_Global.C");
    Global_Reco();
  }

  else if (do_global_fastsim)
  {
    gROOT->LoadMacro("G4_Global.C");
    Global_FastSim();
  }

  //-----------------
  // Calo Trigger Simulation
  //-----------------

  if (do_calotrigger)
  {
    gROOT->LoadMacro("G4_CaloTrigger.C");
    CaloTrigger_Sim();
  }

  //---------
  // Jet reco
  //---------

  if (do_jet_reco)
  {
    gROOT->LoadMacro("G4_Jets.C");
    Jet_Reco();
  }

  if (do_HIjetreco)
  {
    gROOT->LoadMacro("G4_HIJetReco.C");
    HIJetReco();
  }

  //----------------------
  // Simulation evaluation
  //----------------------

  if (do_svtx_eval) Svtx_Eval(string(outputFile) + "_g4svtx_eval.root");

  if (do_cemc_eval) CEMC_Eval(string(outputFile) + "_g4cemc_eval.root");

  if (do_hcalin_eval) HCALInner_Eval(string(outputFile) + "_g4hcalin_eval.root");

  if (do_hcalout_eval) HCALOuter_Eval(string(outputFile) + "_g4hcalout_eval.root");

  if (do_jet_eval) Jet_Eval(string(outputFile) + "_g4jet_eval.root");




  gSystem->Load("libPhotonJet.so");
  PhotonJet *photjet = new PhotonJet(outputFile);
  
  photjet->Set_Isocone_radius(3);
  photjet->set_cluspt_mincut(0.5); //this is just total cluster pt
  photjet->set_directphotonpt_mincut(5); //this is the direct photon min pt
  photjet->set_jetpt_mincut(5.);
  photjet->use_trigger_emulator(1);
  photjet->use_tracked_jets(0);
  photjet->set_eta_lowhigh(-1,1);
  photjet->use_isocone_algorithm(0);
  photjet->set_jetcone_size(4);
  photjet->use_positioncorrection_CEMC(1);
  photjet->set_AA_collisions(0);
  se->registerSubsystem(photjet);





  //--------------
  // IO management
  //--------------

  if (readhits)
  {
    //meta-lib for DST objects used in simulation outputs
    gSystem->Load("libg4dst.so");

    // Hits file
    Fun4AllInputManager *hitsin = new Fun4AllDstInputManager("DSTin");
    hitsin->fileopen(inputFile);
    se->registerInputManager(hitsin);
  }

  if (do_embedding)
  {
    if (embed_input_file == NULL)
    {
      cout << "Missing embed_input_file! Exit";
      exit(3);
    }

    //meta-lib for DST objects used in simulation outputs
    gSystem->Load("libg4dst.so");

    Fun4AllDstInputManager *in1 = new Fun4AllNoSyncDstInputManager("DSTinEmbed");
    //      in1->AddFile(embed_input_file); // if one use a single input file
    in1->AddListFile(embed_input_file);  // RecommendedL: if one use a text list of many input files
    se->registerInputManager(in1);
  }

  if (readhepmc)
  {
    //meta-lib for DST objects used in simulation outputs
    gSystem->Load("libg4dst.so");

    Fun4AllHepMCInputManager *in = new Fun4AllHepMCInputManager("HepMCInput_1");
    se->registerInputManager(in);
    se->fileopen(in->Name().c_str(), inputFile);
    //in->set_vertex_distribution_width(100e-4,100e-4,30,0);//optional collision smear in space, time
    //in->set_vertex_distribution_mean(0,0,1,0);//optional collision central position shift in space, time
    // //optional choice of vertex distribution function in space, time
    //in->set_vertex_distribution_function(PHHepMCGenHelper::Gaus,PHHepMCGenHelper::Gaus,PHHepMCGenHelper::Uniform,PHHepMCGenHelper::Gaus);
    //! embedding ID for the event
    //! positive ID is the embedded event of interest, e.g. jetty event from pythia
    //! negative IDs are backgrounds, .e.g out of time pile up collisions
    //! Usually, ID = 0 means the primary Au+Au collision background
    //in->set_embedding_id(2);
  }
  else
  {
    // for single particle generators we just need something which drives
    // the event loop, the Dummy Input Mgr does just that
    Fun4AllInputManager *in = new Fun4AllDummyInputManager("JADE");
    se->registerInputManager(in);
  }

  if (pileup_collision_rate > 0)
  {
    // pile up simulation.
    // add random beam collisions following a collision diamond and rate from a HepMC stream
    Fun4AllHepMCPileupInputManager *pileup = new Fun4AllHepMCPileupInputManager("HepMCPileupInput");
    se->registerInputManager(pileup);

    const string pileupfile("/sphenix/sim/sim01/sHijing/sHijing_0-12fm.dat");
    pileup->AddFile(pileupfile);  // HepMC events used in pile up collisions. You can add multiple files, and the file list will be reused.
    //pileup->set_vertex_distribution_width(100e-4,100e-4,30,5);//override collision smear in space time
    //pileup->set_vertex_distribution_mean(0,0,0,0);//override collision central position shift in space time
    pileup->set_collision_rate(pileup_collision_rate);

    double time_window_minus = -35000;
    double time_window_plus = 35000;

    if (do_svtx)
    {
      // double TPCDriftVelocity = 6.0 / 1000.0; // cm/ns, which is loaded from G4_SVTX*.C macros
      time_window_minus = -105.5 / TPCDriftVelocity;  // ns
      time_window_plus = 105.5 / TPCDriftVelocity;    // ns;
    }
    pileup->set_time_window(time_window_minus, time_window_plus);  // override timing window in ns
    cout << "Collision pileup enabled using file " << pileupfile << " with collision rate " << pileup_collision_rate
         << " and time window " << time_window_minus << " to " << time_window_plus << endl;
  }

  if (do_DSTReader)
  {
    //Convert DST to human command readable TTree for quick poke around the outputs
    gROOT->LoadMacro("G4_DSTReader.C");

    G4DSTreader(outputFile,  //
                /*int*/ absorberactive,
                /*bool*/ do_svtx,
                /*bool*/ do_pstof,
                /*bool*/ do_cemc,
                /*bool*/ do_hcalin,
                /*bool*/ do_magnet,
                /*bool*/ do_hcalout,
                /*bool*/ do_cemc_twr,
                /*bool*/ do_hcalin_twr,
                /*bool*/ do_magnet,
                /*bool*/ do_hcalout_twr);
  }

  //  Fun4AllDstOutputManager *out = new Fun4AllDstOutputManager("DSTOUT", outputFile);
  // if (do_dst_compress) DstCompress(out);
  //  se->registerOutputManager(out);

  //-----------------
  // Event processing
  //-----------------
  if (nEvents < 0)
  {
    return;
  }
  // if we run the particle generator and use 0 it'll run forever
  if (nEvents == 0 && !readhits && !readhepmc)
  {
    cout << "using 0 for number of events is a bad idea when using particle generators" << endl;
    cout << "it will run forever, so I just return without running anything" << endl;
    return;
  }

  se->run(nEvents);

  //-----
  // Exit
  //-----

  se->End();
  std::cout << "All done" << std::endl;
  delete se;
  gSystem->Exit(0);
}
int Fun4All_G4_EICDetector_LQ_reference(
			      string n="1093",
			      string ebeam="20",
			      string pbeam="250",
			      //string inputFile,
			      string inputFile="/direct/phenix+u/spjeffas/LQGENEP/TestOut.1093event.root",
			      string output="",
			      const char * outputFile = "G4EICDetector.root"
			   )
{
  // Set the number of TPC layer
  const int n_TPC_layers = 40;  // use 60 for backward compatibility only
  
  //Get parameter variables from parameter file
  
  int nEvents;
  stringstream geek(n);
  geek>>nEvents;



  string directory = "/direct/phenix+u/spjeffas/leptoquark/output/"+output+"/";


  //===============
  // Input options
  //===============
  // Either:
  // read previously generated g4-hits files, in this case it opens a DST and skips
  // the simulations step completely. The G4Setup macro is only loaded to get information
  // about the number of layers used for the cell reco code
  //
  // In case reading production output, please double check your G4Setup_sPHENIX.C and G4_*.C consistent with those in the production macro folder
  // E.g. /sphenix/sim//sim01/production/2016-07-21/single_particle/spacal2d/
  const bool readhits = false;
  // Or:
  // read files in HepMC format (typically output from event generators like hijing or pythia)
  const bool readhepmc = false; // read HepMC files
  // Or:
  // read files in EICTree format generated by eicsmear package
  const bool readeictree = true;
  // Or:
  // Use Pythia 8
  const bool runpythia8 = false;
  // Or:
  // Use Pythia 6
  const bool runpythia6 = false;
  // Or:
  // Use HEPGen
  const bool runhepgen = false;
  // Or:
  // Use Sartre
  const bool runsartre = false;



  // Besides the above flags. One can further choose to further put in following particles in Geant4 simulation
  // Use multi-particle generator (PHG4SimpleEventGenerator), see the code block below to choose particle species and kinematics
  const bool particles = false && !readhits;
  // or gun/ very simple single particle gun generator
  const bool usegun = false && !readhits;
  // Throw single Upsilons, may be embedded in Hijing by setting readhepmc flag also  (note, careful to set Z vertex equal to Hijing events)
  const bool upsilons = false && !readhits;

  //======================
  // What to run
  //======================

  // sPHENIX barrel
  bool do_bbc = true;

  bool do_pipe = true;

  bool do_svtx = true;
  bool do_svtx_cell = do_svtx && true;
  bool do_svtx_track = do_svtx_cell && true;
  bool do_svtx_eval = do_svtx_track && true;

  bool do_pstof = false;

  bool do_cemc = true;

  bool do_cemc_cell = true;
  bool do_cemc_twr = true;
  bool do_cemc_cluster = true;
  bool do_cemc_eval = true;

  bool do_hcalin = true;
  bool do_hcalin_cell = true;
  bool do_hcalin_twr = true;
  bool do_hcalin_cluster = true;
  bool do_hcalin_eval = true;

  bool do_cemc_cell = do_cemc && true;
  bool do_cemc_twr = do_cemc_cell && true;
  bool do_cemc_cluster = do_cemc_twr && true;
  bool do_cemc_eval = do_cemc_cluster && true;

  bool do_hcalin = true;
  bool do_hcalin_cell = do_hcalin && true;
  bool do_hcalin_twr = do_hcalin_cell && true;
  bool do_hcalin_cluster = do_hcalin_twr && true;
  bool do_hcalin_eval = do_hcalin_cluster && true;


  bool do_magnet = true;

  bool do_hcalout = true;

  bool do_hcalout_cell = true;
  bool do_hcalout_twr = true;
  bool do_hcalout_cluster = true;
  bool do_hcalout_eval = true;

  bool do_global = true;
  bool do_global_fastsim = false;

  bool do_jet_reco = true;
  bool do_jet_eval = true;

  bool do_fwd_jet_reco = true;
  bool do_fwd_jet_eval = false;

  bool do_hcalout_cell = do_hcalout && true;
  bool do_hcalout_twr = do_hcalout_cell && true;
  bool do_hcalout_cluster = do_hcalout_twr && true;
  bool do_hcalout_eval = do_hcalout_cluster && true;


  // EICDetector geometry - barrel
  bool do_DIRC = true;

  // EICDetector geometry - 'hadron' direction
  bool do_FGEM = true;
  bool do_FGEM_track = do_FGEM &&  false;

  bool do_RICH = true;
  bool do_Aerogel = true;

  bool do_FEMC = true;
  bool do_FEMC_cell = do_FEMC && true;
  bool do_FEMC_twr = do_FEMC_cell && true;
  bool do_FEMC_cluster = do_FEMC_twr && true;
  bool do_FEMC_eval = do_FEMC_cluster && true;

  bool do_FHCAL = true;
  bool do_FHCAL_cell = do_FHCAL && true;
  bool do_FHCAL_twr = do_FHCAL_cell && true;
  bool do_FHCAL_cluster = do_FHCAL_twr && true;
  bool do_FHCAL_eval = do_FHCAL_cluster && true;

  // EICDetector geometry - 'electron' direction
  bool do_EGEM = true;
  bool do_EGEM_track = do_EGEM &&  false;

  bool do_EEMC = true;
  bool do_EEMC_cell = do_EEMC && true;
  bool do_EEMC_twr = do_EEMC_cell && true;
  bool do_EEMC_cluster = do_EEMC_twr && true;
  bool do_EEMC_eval = do_EEMC_cluster && true;

  //do leptoquark analysis modules
  bool do_lepto_analysis = true;

  // Other options
  bool do_global = true;
  bool do_global_fastsim = false;

  bool do_calotrigger = false && do_cemc_twr && do_hcalin_twr && do_hcalout_twr;

  bool do_jet_reco = true;
  bool do_jet_eval = do_jet_reco && true;

  bool do_fwd_jet_reco = true;
  bool do_fwd_jet_eval = do_fwd_jet_reco && true;

  // HI Jet Reco for jet simulations in Au+Au (default is false for
  // single particle / p+p simulations, or for Au+Au simulations which
  // don't care about jets)
  bool do_HIjetreco = false && do_jet_reco && do_cemc_twr && do_hcalin_twr && do_hcalout_twr;

  // Compress DST files
  bool do_dst_compress = false;

  //Option to convert DST to human command readable TTree for quick poke around the outputs
  bool do_DSTReader = false;

  //---------------
  // Load libraries
  //---------------

  gSystem->Load("libfun4all.so");
  gSystem->Load("libg4detectors.so");
  gSystem->Load("libphhepmc.so");
  gSystem->Load("libg4testbench.so");
  gSystem->Load("libg4hough.so");
  gSystem->Load("libg4calo.so");
  gSystem->Load("libg4eval.so");
  gSystem->Load("libeicana.so");

  // establish the geometry and reconstruction setup
  gROOT->LoadMacro("G4Setup_EICDetector.C");
  G4Init(do_svtx,do_cemc,do_hcalin,do_magnet,do_hcalout,do_pipe,do_FGEM,do_EGEM,do_FEMC,do_FHCAL,do_EEMC,do_DIRC,do_RICH,do_Aerogel,n_TPC_layers);

  int absorberactive = 0; // set to 1 to make all absorbers active volumes
  //  const string magfield = "1.5"; // if like float -> solenoidal field in T, if string use as fieldmap name (including path)
  const string magfield = "/phenix/upgrades/decadal/fieldmaps/sPHENIX.2d.root"; // if like float -> solenoidal field in T, if string use as fieldmap name (including path)
  const float magfield_rescale = 1.4/1.5; // scale the map to a 1.4 T field

  //---------------
  // Fun4All server
  //---------------

  Fun4AllServer *se = Fun4AllServer::instance();
  se->Verbosity(0); // uncomment for batch production running with minimal output messages
  // se->Verbosity(Fun4AllServer::VERBOSITY_SOME); // uncomment for some info for interactive running

  // just if we set some flags somewhere in this macro
  recoConsts *rc = recoConsts::instance();
  // By default every random number generator uses
  // PHRandomSeed() which reads /dev/urandom to get its seed
  // if the RANDOMSEED flag is set its value is taken as seed
  // You can either set this to a random value using PHRandomSeed()
  // which will make all seeds identical (not sure what the point of
  // this would be:
  //  rc->set_IntFlag("RANDOMSEED",PHRandomSeed());
  // or set it to a fixed value so you can debug your code
  // rc->set_IntFlag("RANDOMSEED", 12345);

  //-----------------
  // Event generation
  //-----------------

  if (readhits)
    {
      // Get the hits from a file
      // The input manager is declared later
    }
  else if (readhepmc)
    {
      // this module is needed to read the HepMC records into our G4 sims
      // but only if you read HepMC input files
      HepMCNodeReader *hr = new HepMCNodeReader();
      se->registerSubsystem(hr);
    }
  else if (readeictree)
    {
      // this module is needed to read the EICTree style records into our G4 sims
      ReadEICFiles *eicr = new ReadEICFiles();
      eicr->OpenInputFile(inputFile);

      se->registerSubsystem(eicr);
    }
  else if (runpythia8)
    {
      gSystem->Load("libPHPythia8.so");

      PHPythia8* pythia8 = new PHPythia8();
      // see coresoftware/generators/PHPythia8 for example config
      pythia8->set_config_file("/direct/phenix+u/spjeffas/coresoftware/generators/PHPythia8/phpythia8.cfg");
      se->registerSubsystem(pythia8);

      HepMCNodeReader *hr = new HepMCNodeReader();
      se->registerSubsystem(hr);
    }
  else if (runpythia6)
    {
      gSystem->Load("libPHPythia6.so");

      PHPythia6 *pythia6 = new PHPythia6();
      // see coresoftware/generators/PHPythia6 for example config
      pythia6->set_config_file("/direct/phenix+u/spjeffas/coresoftware/generators/PHPythia6/phpythia6_ep.cfg");
      se->registerSubsystem(pythia6);

      HepMCNodeReader *hr = new HepMCNodeReader();
      se->registerSubsystem(hr);
    }
  else if (runhepgen)
    {
      gSystem->Load("libsHEPGen.so");

      sHEPGen *hepgen = new sHEPGen();
      // see HEPGen source directory/share/vggdata for required .dat files
      // see HEPGen source directory/share/datacards for required datacard files
      hepgen->set_datacard_file("hepgen_dvcs.data");
      hepgen->set_momentum_electron(-20);
      hepgen->set_momentum_hadron(250);
      se->registerSubsystem(hepgen);

      HepMCNodeReader *hr = new HepMCNodeReader();
      se->registerSubsystem(hr);
    }
  else if (runsartre)
    {
      // see coresoftware/generators/PHSartre/README for setup instructions
      // before running:
      // setenv SARTRE_DIR /opt/sphenix/core/sartre-1.20_root-5.34.36
      gSystem->Load("libPHSartre.so");

      PHSartre* mysartre = new PHSartre();
      // see coresoftware/generators/PHSartre for example config
      mysartre->set_config_file("sartre.cfg");

      // particle trigger to enhance forward J/Psi -> ee
      PHSartreParticleTrigger* pTrig = new PHSartreParticleTrigger("MySartreTrigger");
      pTrig->AddParticles(-11);
      //pTrig->SetEtaHighLow(4.0,1.4);
      pTrig->SetEtaHighLow(1.0,-1.1);  // central arm
      pTrig->PrintConfig();
      mysartre->register_trigger((PHSartreGenTrigger *)pTrig);
      se->registerSubsystem(mysartre);

      HepMCNodeReader *hr = new HepMCNodeReader();
      se->registerSubsystem(hr);
    }

  // If "readhepMC" is also set, the particles will be embedded in Hijing events
  if(particles)
    {
      // toss low multiplicity dummy events
      PHG4SimpleEventGenerator *gen = new PHG4SimpleEventGenerator();

      //gen->add_particles("e-",5); // mu+,e+,proton,pi+,Upsilon
      //gen->add_particles("e+",5); // mu-,e-,anti_proton,pi-
      gen->add_particles("tau-",1); // mu-,e-,anti_proton,pi-
      if (readhepmc) {
        gen->set_reuse_existing_vertex(true);
        gen->set_existing_vertex_offset_vector(0.0,0.0,0.0);
      } else {
        gen->set_vertex_distribution_function(PHG4SimpleEventGenerator::Uniform,
                                              PHG4SimpleEventGenerator::Uniform,
                                              PHG4SimpleEventGenerator::Uniform);
        gen->set_vertex_distribution_mean(0.0,0.0,0.0);
        gen->set_vertex_distribution_width(0.0,0.0,5.0);
      }
      gen->set_vertex_size_function(PHG4SimpleEventGenerator::Uniform);
      gen->set_vertex_size_parameters(0.0,0.0);
      gen->set_eta_range(0.1, 0.1);
      //gen->set_eta_range(3.0, 3.0); //EICDetector FWD
      gen->set_phi_range(TMath::Pi()/2-0.1, TMath::Pi()/2-0.1);
      //gen->set_phi_range(TMath::Pi()/2-0.1, TMath::Pi()/2-0.1);
      gen->set_p_range(30.0, 30.0);

      //gen->add_particles("pi-",1); // mu+,e+,proton,pi+,Upsilon
      //gen->add_particles("pi+",100); // 100 pion option
      if (readhepmc)
        {
          gen->set_reuse_existing_vertex(true);
          gen->set_existing_vertex_offset_vector(0.0, 0.0, 0.0);
        }
      else
        {
          gen->set_vertex_distribution_function(PHG4SimpleEventGenerator::Uniform,
                                                PHG4SimpleEventGenerator::Uniform,
                                                PHG4SimpleEventGenerator::Uniform);
          gen->set_vertex_distribution_mean(0.0, 0.0, 0.0);
          gen->set_vertex_distribution_width(0.0, 0.0, 0.0);
        }
      gen->set_vertex_size_function(PHG4SimpleEventGenerator::Uniform);
      gen->set_vertex_size_parameters(0.0, 0.0);
      gen->set_eta_range(-1.0, 1.0);
      gen->set_phi_range(-1.0 * TMath::Pi(), 1.0 * TMath::Pi());
      //gen->set_pt_range(0.1, 50.0);
      gen->set_pt_range(0.1, 20.0);

      gen->Embed(1);
      gen->Verbosity(0);

      se->registerSubsystem(gen);
    }
  if (usegun)
    {
      // PHG4ParticleGun *gun = new PHG4ParticleGun();
      // gun->set_name("anti_proton");
      // gun->set_name("geantino");
      // gun->set_vtx(0, 0, 0);
      // gun->set_mom(10, 0, 0.01);
      // gun->AddParticle("geantino",1.7776,-0.4335,0.);
      // gun->AddParticle("geantino",1.7709,-0.4598,0.);
      // gun->AddParticle("geantino",2.5621,0.60964,0.);
      // gun->AddParticle("geantino",1.8121,0.253,0.);
      // se->registerSubsystem(gun);
      PHG4ParticleGenerator *pgen = new PHG4ParticleGenerator();
      pgen->set_name("e-");
      pgen->set_z_range(0,0);
      pgen->set_eta_range(0.01,0.01);
      pgen->set_mom_range(10,10);
      pgen->set_phi_range(-1.0 * TMath::Pi(), 1.0 * TMath::Pi());
      se->registerSubsystem(pgen);
    }

  // If "readhepMC" is also set, the Upsilons will be embedded in Hijing events, if 'particles" is set, the Upsilons will be embedded in whatever particles are thrown
  if(upsilons)
    {
      // run upsilons for momentum, dca performance, alone or embedded in Hijing

      PHG4ParticleGeneratorVectorMeson *vgen = new PHG4ParticleGeneratorVectorMeson();
      vgen->add_decay_particles("e+","e-",0); // i = decay id
      // event vertex
      if (readhepmc || particles)
        {
          vgen->set_reuse_existing_vertex(true);
        }
      else
        {
          vgen->set_vtx_zrange(-10.0, +10.0);
        }

      // Note: this rapidity range completely fills the acceptance of eta = +/- 1 unit
      vgen->set_rapidity_range(-1.0, +1.0);
      vgen->set_pt_range(0.0, 10.0);

      int istate = 1;

      if(istate == 1)
        {
          // Upsilon(1S)
          vgen->set_mass(9.46);
          vgen->set_width(54.02e-6);
        }
      else if (istate == 2)
        {
          // Upsilon(2S)
          vgen->set_mass(10.0233);
          vgen->set_width(31.98e-6);
        }
      else
        {
          // Upsilon(3S)
          vgen->set_mass(10.3552);
          vgen->set_width(20.32e-6);
        }

      vgen->Verbosity(0);
      vgen->Embed(2);
      se->registerSubsystem(vgen);

      cout << "Upsilon generator for istate = " << istate << " created and registered "  << endl;
    }

  if (!readhits)
    {
      //---------------------
      // Detector description
      //---------------------

      G4Setup(absorberactive, magfield, TPythia6Decayer::kAll,
              do_svtx,do_cemc,do_hcalin,do_magnet,do_hcalout,do_pipe,
              do_FGEM,do_EGEM,do_FEMC,do_FHCAL,do_EEMC,do_DIRC,do_RICH,do_Aerogel,
              magfield_rescale);
   
    }

  //---------
  // BBC Reco
  //---------

  if (do_bbc)
    {
      gROOT->LoadMacro("G4_Bbc.C");
      BbcInit();
      Bbc_Reco();
    }

  //------------------
  // Detector Division
  //------------------

  if (do_svtx_cell) Svtx_Cells();

  if (do_cemc_cell) CEMC_Cells();

  if (do_hcalin_cell) HCALInner_Cells();

  if (do_hcalout_cell) HCALOuter_Cells();

  if (do_FEMC_cell) FEMC_Cells();

  if (do_FHCAL_cell) FHCAL_Cells();

  if (do_EEMC_cell) EEMC_Cells();

  //-----------------------------
  // CEMC towering and clustering
  //-----------------------------

  if (do_cemc_twr) CEMC_Towers();
  if (do_cemc_cluster) CEMC_Clusters();

  //-----------------------------
  // HCAL towering and clustering
  //-----------------------------

  if (do_hcalin_twr) HCALInner_Towers();
  if (do_hcalin_cluster) HCALInner_Clusters();

  if (do_hcalout_twr) HCALOuter_Towers();
  if (do_hcalout_cluster) HCALOuter_Clusters();

  //-----------------------------
  // e, h direction Calorimeter  towering and clustering
  //-----------------------------

  if (do_FEMC_twr) FEMC_Towers();
  if (do_FEMC_cluster) FEMC_Clusters();

  if (do_FHCAL_twr) FHCAL_Towers();
  if (do_FHCAL_cluster) FHCAL_Clusters();

  if (do_EEMC_twr) EEMC_Towers();
  if (do_EEMC_cluster) EEMC_Clusters();

  if (do_dst_compress) ShowerCompress();

  //--------------
  // SVTX tracking
  //--------------

  if (do_svtx_track) Svtx_Reco();

  //--------------
  // FGEM tracking
  //--------------

  if(do_FGEM_track) FGEM_FastSim_Reco();

  //--------------
  // EGEM tracking
  //--------------

  if(do_EGEM_track) EGEM_FastSim_Reco();

  //-----------------
  // Global Vertexing
  //-----------------

  if (do_global)
    {
      gROOT->LoadMacro("G4_Global.C");
      Global_Reco();
    }

  else if (do_global_fastsim)
    {
      gROOT->LoadMacro("G4_Global.C");
      Global_FastSim();
    }

  //-----------------
  // Calo Trigger Simulation
  //-----------------

  if (do_calotrigger)
    {
      gROOT->LoadMacro("G4_CaloTrigger.C");
      CaloTrigger_Sim();
    }

  //---------
  // Jet reco
  //---------

  if (do_jet_reco)
    {
      gROOT->LoadMacro("G4_Jets.C");
      Jet_Reco();
    }

  if (do_HIjetreco) {
    gROOT->LoadMacro("G4_HIJetReco.C");
    HIJetReco();
  }

  if (do_fwd_jet_reco)
    {
      gROOT->LoadMacro("G4_FwdJets.C");
      Jet_FwdReco();
    }

  //----------------------
  // Simulation evaluation
  //----------------------
  
  
  if (do_svtx_eval) Svtx_Eval(directory+"g4svtx_p"+pbeam+"_e"+ebeam+"_"+n+"events_eval.root");
  
  if (do_cemc_eval) CEMC_Eval(directory+"g4cemc_p"+pbeam+"_e"+ebeam+"_"+n+"events_eval.root");

  if (do_hcalin_eval) HCALInner_Eval(directory+"g4hcalin_p"+pbeam+"_e"+ebeam+"_"+n+"events_eval.root");

  if (do_hcalout_eval) HCALOuter_Eval(directory+"g4hcalout_p"+pbeam+"_e"+ebeam+"_"+n+"events_eval.root");

  if (do_jet_eval) Jet_Eval(directory+"g4jet_p"+pbeam+"_e"+ebeam+"_"+n+"events_eval.root");

  if (do_fwd_jet_eval) Jet_FwdEval(directory+"g4fwdjet_p"+pbeam+"_e"+ebeam+"_"+n+"events_eval.root");
  
  if(do_lepto_analysis){
    gROOT->LoadMacro("G4_Lepto.C");
    G4_Lepto(directory+"LeptoAna_p"+pbeam+"_e"+ebeam+"_"+n+"events");
  }
  

  
 
  
  //--------------
  // IO management
  //--------------

  if (readhits)
    {
      // Hits file
      Fun4AllInputManager *hitsin = new Fun4AllDstInputManager("DSTin");
      hitsin->fileopen(inputFile);
      se->registerInputManager(hitsin);
    }
  if (readhepmc)
    {
      Fun4AllInputManager *in = new Fun4AllHepMCInputManager( "DSTIN");
      se->registerInputManager( in );
      se->fileopen( in->Name().c_str(), inputFile );
    }
  else
    {
      // for single particle generators we just need something which drives
      // the event loop, the Dummy Input Mgr does just that
      Fun4AllInputManager *in = new Fun4AllDummyInputManager( "JADE");
      se->registerInputManager( in );
    }

  if (do_DSTReader)
    {
      //Convert DST to human command readable TTree for quick poke around the outputs
      gROOT->LoadMacro("G4_DSTReader_EICDetector.C");

      G4DSTreader_EICDetector( outputFile, //
                               /*int*/ absorberactive ,
                               /*bool*/ do_svtx ,
                               /*bool*/ do_cemc ,
                               /*bool*/ do_hcalin ,
                               /*bool*/ do_magnet ,
                               /*bool*/ do_hcalout ,
                               /*bool*/ do_cemc_twr ,
                               /*bool*/ do_hcalin_twr ,
                               /*bool*/ do_magnet  ,
                               /*bool*/ do_hcalout_twr,
                               /*bool*/ do_FGEM,
                               /*bool*/ do_EGEM,
                               /*bool*/ do_FHCAL,
                               /*bool*/ do_FHCAL_twr,
                               /*bool*/ do_FEMC,
                               /*bool*/ do_FEMC_twr,
                               /*bool*/ do_EEMC,
                               /*bool*/ do_EEMC_twr
                               );
    }

  Fun4AllDstOutputManager *out = new Fun4AllDstOutputManager("DSTOUT", outputFile);
  if (do_dst_compress) DstCompress(out);
  se->registerOutputManager(out);

  //-----------------
  // Event processing
  //-----------------
  if (nEvents < 0)
    {
      return;
    }
  // if we run the particle generator and use 0 it'll run forever
  if (nEvents == 0 && !readhits && !readhepmc)
    {
      cout << "using 0 for number of events is a bad idea when using particle generators" << endl;
      cout << "it will run forever, so I just return without running anything" << endl;
      return;
    }

  se->run(nEvents);

  //-----
  // Exit
  //-----

  se->End();
  std::cout << "All done" << std::endl;
  delete se;
  gSystem->Exit(0);
}