// FileName: reco_MC_daikon_near_cosmic_cedar_phy_srsafitter.C

// Created: 6 November 2007
// based on reco_MC_daikon_far_cosmic_cedar_phy_srsafitter.C
// with near detector settings from reco_MC_daikon_near_cosmic_cedar_phy.C

// Last Modified: April 23, 2007
// Most Recent Modifications:
// June 21, 2007: for daikon, uses safitter
// Jan. 09, 2007: (JAB) Adding some data quality commands from A. Blake
// Oct. 30, 2006: (JAB) Adding nRun and nSkip params
// Oct. 26, 2006: (JAB) Adjusting filtering and CandChop Settings
// Sept. 14, 2006: (JAB) Removing Snts
// August 25, 2006: (JAB) Branching for Cedar and
//			   setting fTitle
// July 20, 2006: (JAB) Branching for R1-24 tests

// Usage
// cp <path>/reco_MC_daikon_far_cosmic_cedar_phy_safitter.C reco_MC.C
// loon -bq "reco_MC.C(nSkip,nRun)" <reroot_file>

/////////////////////////////////////////////////////////
// Description of this                                 //
// This file will produce an MC sim of a cosmic stream //
//  This is only meant to do MC FarDet processing      //
//  for nue, numu, or nutau  in development.           //
//  Simulations processing takes place in the Reco     //
//   path, while reconstruction occurs in the "Reco1"  //
//   path.                                             //
//  Each output stream requires its own processing     //
//   branch and so there are small offshoot branches   //
// Uses: CandChop                                      //
//       CandTrackCam                                  //
//       CandFitTrackCam                               //
//       GeoGeometry (in reco)                         //
// Demuxer: Alt/Cambridge                              //
//                                                     //
// This is the Diakon Version                          //
//
// This version uses safitter
//
//                                                     //
// Output:                                             //
// Output Files:                                       //
//  CandS.root - candidate output file                 //
//  ntupleStS.root - NtpSt ntuple output               //
//                                                     //
/////////////////////////////////////////////////////////

class JobC;

int LoadLibraries();
int GetRunNumber();

void SetCalibrator();

void SetCandOutputWithBNtp(JobCModule &jcm, TString file);
void SetCandOutputNoBNtp(JobCModule &jcm, TString file);
void SetNtpStOutputWithBNtp(JobCModule &jcm, TString file);
void SetNtpStOutputNoBNtp(JobCModule &jcm, TString file);
void SetNtpStOutputNoBNtpSA(JobCModule &jcm, TString file);

void SetMSGLevels(JobC &jc);

void reco_MC(int nSkip=0, int nRun=100000)
{
  reco_MC_daikon_near_cosmic_cedar_phy_srsafitter(nSkip, nRun);
}

void reco_MC_daikon_near_cosmic_cedar_phy_srsafitter(int nSkip=0, int nRun=100000)
{
  LoadLibraries();

  JobC jc;

  //Create path - first the reroot job
  jc.Path.Create("Reco",
                 "RerootToTruthModule::Get "
                 "PhotonTransport::Get "
                 "DetSim::Get "
		 );

  //And Now the Normal Reco chain
  jc.Path.Create("Reco1",
		 "NoiseFilterModule::Ana "
		 "RecordSetupModule::Get "
		 "DigitListModule::Get "
		 "DigitListModule::Reco "
		 "StripSRListModule::Reco "
		 "SliceSRListModule::Reco "
		 "TrackCamListModule::Reco "
		 "FitTrackCamListModule::Reco "
		 "ClusterSRListModule::Reco "
		 "ShowerSRListModule::Reco "
		 "EventSRListModule::Reco "
		 "RecordSetupModule::Reco "
		 );

  //Attach the normal reco chain after the reroot path
  jc.Path.Attach("Reco","Reco1");

  //Input Parameters
  jc.Input.Set("Format=reroot");
  jc.Input.Set("Streams=DaqSnarl");   //takes reroot data as input

   // Set up RerootExodus to build the event as MC (instead of Reroot)
  RerootExodus::SetVldSimFlag(SimFlag::kMC);

  //turn off all filters
  jc.Path("Reco").SetAllFilters(0);
  jc.Path("Reco1").SetAllFilters(0);

  //////////////////////////////////////
  //Configure Reconstruction Software for Near Det MC "Spill" data .
  // For a full description of the different possible module options see the
  //   Document:  ConfigOptions.txt

  //Settings for PhotonTransport Module
  JobCModule& photon=jc.Path("Reco").Mod("PhotonTransport");
  photon.Set("GeVPerMip=0.001792");

  jc.Path("Reco1").Mod("SliceSRListModule").Set("SliceListAlgConfig=NearCosmic");
  jc.Path("Reco1").Mod("ClusterSRListModule").Set("ClusterListAlgConfig=NearCosmic");
  jc.Path("Reco1").Mod("ShowerSRListModule").Set("ShowerListAlgConfig=NearCosmic");


  jc.Path("Reco1").Mod("TrackCamListModule").Set("TrackListAlgConfig=Cosmic");
  jc.Path("Reco1").Mod("TrackCamListModule").Set("NameListIn=CandSliceList");
  jc.Path("Reco1").Mod("TrackCamListModule").Set("NameListOut=CandTrackSRList");
  jc.Path("Reco1").Mod("FitTrackCamListModule").Set("NameListIn=CandTrackSRList");
  //  jc.Path("Reco1").Mod("FitTrackCamListModule").Set("NameListOut=CandFitTrackSRList"); //added for safitter

  jc.Path("Reco1").Mod("EventSRListModule").Set("EventListAlgorithm=AlgEventSRList");

  jc.Path("Reco1").Mod("EventSRListModule").Set("EventListAlgConfig=NearCosmic");

  //Set up the conditions for the CandSubShower Package
  jc.Path("Reco1").Mod("ShowerSRListModule").Set("ShowerListAlgorithm=AlgShowerSRList");
  jc.Path("Reco1").Mod("ShowerSRListModule").Set("ShowerListAlgConfig=default");
  jc.Path("Reco1").Mod("ShowerSRListModule").Set("ListOut=CandShowerSRList");

  jc.Path("Reco1").Mod("StripSRListModule").Set("ListIn=canddigitlist");


  ////////////////////////////////////////////////////////////////

  //////////////////////////////////////

  // Set the simulated date of the events as to allow for consistent calibration
  // RerootExodus::SetOverrideVldTimeStamp();

  // Set Ugli to use only database.
  UgliLoanPool::SetAlwaysUseDbi(true);

  // Use GeoGeometry for reconstruction instead of UgliGeometry
  UgliLoanPool::Instance()->SetUseGeo(true);

  SetCalibrator();

  //  End of Configuration settings     //
  ////////////////////////////////////////

  ////////////////////////////////////////////////////////////////
  //Display the Configuration of modules

  jc.Path("Reco").Mod("RerootToTruthModule").Report();
  jc.Path("Reco").Mod("PhotonTransport").Report();
  jc.Path("Reco").Mod("DetSim").Report();
  //  jc.Path("Reco1").Mod("DeMuxDigitListModule").Report();
  jc.Path("Reco1").Mod("StripSRListModule").Report();
  jc.Path("Reco1").Mod("ShowerSRListModule").Report();
  jc.Path("Reco1").Mod("TrackCamListModule").Report();
  jc.Path("Reco1").Mod("FitTrackCamListModule").Report();
  //////////////////////////////////////////////////////////////

  ////////////////////////////////////////////////////////////////

  /////////////////////////////////////////////////
  //    Setting the Output Paths                 //
  //  - This script produces the 3 output        //
  //    streams, cand, snts, sntp                //
  /////////////////////////////////////////////////

  //Set Candidate Output to CandA.root (all of the snarls included in output)
  //this will become the .cand. file
  jc.Path.Create("CandOut",
		 "Output::Put "
                 );
  SetCandOutputNoBNtp(jc.Path("CandOut").Mod("Output"), "CandS.root");
  jc.Path.Attach("Reco1", "CandOut");

  //Ntuple record has its own output file so needs its own output module
  jc.Path.Create("NtpSR",
	         "NtpStModule::Get "
	         "NtpSRModule::Reco "
		 "NtpMCModule::Reco " //Necessary to write the MC info tree
                 "NtpTHModule::Reco " //Necessary to write the MC th tree
		 // 	 "Output::Put "
                 "FitTrackSAListModule::Reco "
                 "NtpFitSAModule::Reco "
		 "Output::Put "
		 );
  jc.Path("NtpSR").Mod("NtpMCModule").Set("UseStandard=1"); // use NtpSt
  jc.Path("NtpSR").Mod("NtpTHModule").Set("UseStandard=1"); // use NtpSt
  jc.Path("NtpSR").Mod("NtpSRModule").Set("UseStandard=1"); // use NtpSt



  jc.Path("NtpSR").Mod("FitTrackSAListModule").Set("ListIn=CandFitTrackCamList");
  //  jc.Path("NtpSR").Mod("Output").Set("FileName=ntpSA.root");
  // jc.Path.Attach("Reco","NtpSA");
  jc.Path("NtpSR").Mod("FitTrackSAListModule").Report();

  const char *BaseRel = getenv("SRT_BASE_RELEASE");
  const char *RootRel = getenv("ROOTSYS");

  string RootVer(RootRel);
  RootVer.replace(0,RootVer.rfind("/")+1,"");

  char RecTitle[100];
  sprintf(RecTitle, "RecordTitle=CEDAR_PHY(minossoft:%s,root:%s,Daikon,SAFitter)", BaseRel, RootVer.c_str());

  jc.Path("NtpSR").Mod("NtpStModule").Set(RecTitle);

  SetNtpStOutputNoBNtpSA(jc.Path("NtpSR").Mod("Output"), "ntupleStS.root");
  jc.Path.Attach("Reco1","NtpSR");



  //////////////////////////////////////////////////////
  ///         End of Output Settings                ////
  //////////////////////////////////////////////////////

  SetMSGLevels(jc);

  //Other Run Options
  //  jc.Path("Reco").Run(100);  //Run over the first 100 snarls
    jc.Input.Next(nSkip);  //Skip nSkip Snarls
    jc.Path("Reco").Run(nRun);
  jc.Path("Reco").Report();

  //Get Message Statistics
  jc.Msg.Stats();

}


//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

//  Everything from this point forward are sub-functions        //

int LoadLibraries()
{

  // Link dynamic libraries
  gSystem->Load("libDataUtil");
  gSystem->Load("libRecoBase");
  gSystem->Load("libNoiseFilter");
  gSystem->Load("libFilterDigitSR");
  gSystem->Load("libBField");
  gSystem->Load("libGeoGeometry");
  gSystem->Load("libNumericalMethods");
  gSystem->Load("libSwimmer");
  gSystem->Load("libDeMux");
  gSystem->Load("libCandStripSR");
  gSystem->Load("libCandSliceSR");
  gSystem->Load("libCandChop");
  gSystem->Load("libCandTrackSR");
  gSystem->Load("libCandTrackCam");
  gSystem->Load("libCandClusterSR");
  gSystem->Load("libCandSubShowerSR");
  gSystem->Load("libCandShowerSR");
  gSystem->Load("libCandFitTrackSR");
  gSystem->Load("libCandFitTrackCam");
  gSystem->Load("libCandEventSR");
  gSystem->Load("libVertexFinder");
  gSystem->Load("libTimeCalibratorSR");
  gSystem->Load("libAstroUtil");
  gSystem->Load("libDcsUser");
  gSystem->Load("libCandMorgue");

  gSystem->Load("libCandNtupleSR");
  gSystem->Load("libMCNtuple");
  gSystem->Load("libTruthHelperNtuple");
  gSystem->Load("libStandardNtuple");
  gSystem->Load("libPhotonTransport");
  gSystem->Load("libDetSim");
  gSystem->Load("libMCNtupleModule");
  gSystem->Load("libCandNtupleSRModule");
  gSystem->Load("libTruthHelperNtupleModule");
  gSystem->Load("libStandardNtupleModule");

  gSystem->Load("libCandShield");
  gSystem->Load("libAltDeMux");
  gSystem->Load("libFiltration");
  gSystem->Load("libNtpFitSA");
  gSystem->Load("libCandFitTrackSA");
  gSystem->Load("libNtpFitSAModule");
}

void SetCalibrator()
{
  Calibrator& cal = Calibrator::Instance();
  cal.Set("TimeCalibrator", "SimpleCalScheme");
   //PeCalibrator changed April 23,2007
  cal.Set("PeCalibrator", "PEGainAggCalScheme");
// cal.Set("PeCalibrator",   "PEGainCalScheme");
  cal.Set("VALinCalibrator","SimpleCalScheme");
  cal.Set("DriftCalibrator","MuonDriftCalScheme");  //changed to MuonDriftCalScheme, requested by Jeff Hartnell
  cal.Set("LinCalibrator",  "QuadLinearityCalScheme");
  cal.Set("StripCalibrator","StripToStripCalScheme");
  cal.Set("AttenCalibrator","StripAttenCalScheme");
  cal.Set("MIPCalibrator",  "MIPCalScheme");
  cal.Set("Thermometer",    "SimpleCalScheme");

  //SpectrometerFudge added April 23,2007
  //this should be removed after database entry is updated
  Calibrator::StripCalibrator().Set("SpectrometerFudge=1.16");


}


int GetRunNumber(){
  ////////////////////////////////////////////////////////
  //Get the run number from the Input file name
  //Allows us to set the name of the dst file
  JobCEnv& jce = JobCEnv::Instance();
  string filename = jce.GetFileName(0);
  string rnumstring = filename.substr(filename.find_last_of("_")-8,8);
  int run = atoi(rnumstring.c_str());
//  string srnstring = filename.substr(filename.find_last_of("_")+1,4);

  return run;
}




void SetCandOutputWithBNtp(JobCModule &jcm, TString file){

  jcm.Cmd("DefineStream Config ConfigRecord");
  jcm.Cmd("DefineStream NtpBDLite NtpBDLiteRecord");
  jcm.Set("Streams=NtpBDLite,Cand,Config,DaqSnarl");
  jcm.Set("FileName="+file);
}

void SetCandOutputNoBNtp(JobCModule &jcm, TString file){

  jcm.Cmd("DefineStream Config ConfigRecord");
  jcm.Set("Streams=SimSnarl,Cand,Config,DaqSnarl");
  jcm.Set("FileName="+file);
}

void SetNtpStOutputWithBNtp(JobCModule &jcm, TString file){
  jcm.Cmd("DefineStream NtpSt NtpStRecord");
  jcm.Cmd("DefineStream NtpBDLite NtpBDLiteRecord");
  jcm.Set("Streams=NtpBDLite,NtpSt");
  jcm.Set("FileName="+file);
}

void SetNtpStOutputNoBNtp(JobCModule &jcm, TString file){
  jcm.Cmd("DefineStream NtpSt NtpStRecord");
  jcm.Set("Streams=NtpSt");
  jcm.Set("FileName="+file);
}

void SetNtpStOutputNoBNtpSA(JobCModule &jcm, TString file){
  jcm.Cmd("DefineStream NtpSt NtpStRecord");
   jcm.Cmd("DefineStream NtpFitSA NtpFitSARecord");
  jcm.Set("Streams=NtpSt,NtpFitSA");
  //  jcm.Set("Streams=NtpFitSA");
  jcm.Set("FileName="+file);


}



void SetMSGLevels(JobC &jc){
  //  jc.Msg.SetLevel("FitTrackSR","Warning");
  jc.Msg.SetLevel("TrackCam","Error");
  jc.Msg.SetLevel("TrackCamListModule","Error");
  jc.Msg.SetLevel("NoiseFilter","Fatal");
  jc.Msg.SetLevel("Cand","Error");
  jc.Msg.SetLevel("Calibrator","Fatal");
  jc.Msg.SetLevel("Dbi","Fatal");
  jc.Msg.SetLevel("DetSim","Error");
  jc.Msg.SetLevel("Reroot","Error");
  jc.Msg.SetLevel("Photon","Fatal");

  jc.Msg.SetLevel("Plex","Error");

  jc.Msg.SetLevel("SubShowerSR","Error");
  jc.Msg.SetLevel("AlgFitTrackSR","Error");

  jc.Msg.SetLevel("FitTrackSA","Error");
}
