// FileName: reco_MC_daikon_far_cosmic_cedar_phy_srsafitter.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 Set_TSQL_Override();

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_far_cosmic_cedar_phy_srsafitter(nSkip, nRun);
}

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

  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 "
                 "FilterDigitListModule::Reco "
                 "FilterLIModule::Ana "
		 "ChopModule::Reco "
		 "BiggestChopModule::Reco "
		 "DeMuxDigitListModule::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(1); // CandChop crashes in cedar otherwise
  jc.Path("Reco1").SetAllFilters(0);

  //////////////////////////////////////
  //Configure Reconstruction Software for Far 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.001786");//was 0.001737 and 0.001730
  //This setting was updated by Jeff Hartnell on 26/Apr/2007                          
  //jc.Path("Reco").Mod("RerootToTruthModule").Set("GetApplyRollback=0"); 
  //probably not needed for new daikon mc files
               
  jc.Path("Reco1").Mod("FilterLIModule").Set("LIFinderName=SimplePatternFinder");
  //This setting given by Andy Blake 1/9/2007 to filter out the bulk of the Light Injection
  jc.Path("Reco1").Mod("FilterLIModule").Set("MaxNDigits=1100");

  jc.Path("Reco1").Mod("ChopModule").Set("ChopAlgorithm=AlgChopListFar");
  jc.Path("Reco1").Mod("BiggestChopModule").Set("MinEnergy=0.0"); //No cut.
  jc.Path("Reco1").Mod("BiggestChopModule").Set("OmitLiEvents=1"); //kill LI
  jc.Path("Reco1").Mod("BiggestChopModule").Set("LiVetoWindowLow=-1.0e-6");
  jc.Path("Reco1").Mod("BiggestChopModule").Set("LiVetoWindowHigh=31.0e-6");

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

  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=FarCosmic");
  jc.Path("Reco1").Mod("DeMuxDigitListModule").Set("NameListOut=altdemux");
  jc.Path("Reco1").Mod("DeMuxDigitListModule").Set("SwitchPersToTemp=1");
  //SwitchPersToTemp=1 Do not write out original CandDigitList
  //SwitchPersToTemp=0 Do write out original CandDigitList
  jc.Path("Reco1").Mod("DeMuxDigitListModule").Set("DeMuxDigitListAlgConfig=devel");
  jc.Path("Reco1").Mod("StripSRListModule").Set("ListIn=altdemux");
  //////////////////////////////////////
  //Cosmics's filter parameters
  jc.Path("Reco1").Mod("FilterDigitListModule").Set("FilterDigitListAlgorithm=AlgFilterDigitList");
  jc.Path("Reco1").Mod("FilterDigitListModule").Set("SwitchPersToTemp=1");
  //Don't write out original 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 Set_TSQL_Override()
{
  // decide whether to flip bfield ... based on file name
  JobCEnv& jce = JobCEnv::Instance();
  std::string filename = gSystem->BaseName(jce.GetFileName(0));
  cout << endl << "processing file: " << filename << endl;

  const char* tmppth = gSystem->Getenv("ASCII_DB_PATH");
  if ( ! tmppth ) tmppth = 
                    "$SRT_PUBLIC_CONTEXT/Production/asciidb/cedar_daikon";
  std::string asciidbpath = gSystem->ExpandPathName(tmppth);


  std::string asciidbset = "";

  // automagically switch direction of reverse field running
  // reversed field daikon files are n1tb2rrrr or f2tb2rrrr
  // the "2" before the run # is the relevant flag
  char bfield_dirchar = filename[4];
  if ( bfield_dirchar == '2' ) {
    asciidbset = "brev";
    cout << "Override BField (reverse) based on filename." << endl << endl;
  }

  // set the asciidbset if the env variable is set ... even if the
  // file name indicates we should use "brev"
  const char* tmpset = gSystem->Getenv("ASCII_DB_SET");
  if ( tmpset ) {
    asciidbset = tmpset;
    cout << "Select ASCII DB set \"" << asciidbset 
         << "\" based on ASCII_DB_SET." << endl << endl;
  }

  // only if an asciidbset has been chosen do we use add to the URL
  if ( asciidbset != "" ) {
    std::string tsql_url_orig = gSystem->Getenv("ENV_TSQL_URL");
    std::string first_url     = tsql_url_orig.substr(0,tsql_url_orig.find(";"));
    std::string base_url      = first_url.substr(0,first_url.find_last_of("/"));
    // assume "temp" DB follows the first URL structure
    std::string tsql_url_add  = base_url +
      "/temp#" + asciidbpath + "/" + asciidbset + "/catalogue.db";
  
    std::string tsql_whole    = tsql_url_add + ";" + tsql_url_orig;
    gSystem->Setenv("ENV_TSQL_URL",tsql_whole.c_str());
  }

}

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",  "PulserLinearityCalScheme");
  cal.Set("StripCalibrator","StripToStripCalScheme");
  cal.Set("AttenCalibrator","StripAttenCalScheme");
  cal.Set("MIPCalibrator",  "MIPCalScheme");
  cal.Set("Thermometer",    "SimpleCalScheme");



}


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);

  //jc.Path("NtpSR").Mod("Output").Cmd("DefineStream NtpFitSA NtpFitSARecord");
  //  jc.Path("NtpSR").Mod("Output").Set("Streams=NtpFitSA");
 
}



void SetMSGLevels(JobC &jc){
  jc.Msg.SetLevel("FitTrackSR","Warning");
  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","Warning");

  jc.Msg.SetLevel("Per","Fatal");
  jc.Msg.SetLevel("Io", "Fatal");
  jc.Msg.SetLevel("DeMuxDigitListModule","Error");
  jc.Msg.SetLevel("Plex","Error");

  jc.Msg.SetLevel("AltDeMuxModule","Error");
  jc.Msg.SetLevel("AltDeMux","Fatal");
  jc.Msg.SetLevel("AlgAltDeMux","Fatal");
  jc.Msg.SetLevel("AlgShowerSS", "Warning");
  jc.Msg.SetLevel("SubShowerSR","Error");
  jc.Msg.SetLevel("AlgFitTrackSR", "Warning");

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