// FileName: reco_near_spill_cedar.C
// Last Modified: Sept 14, 2006
// Most Recent Modifications:
// Sept. 14, 2006: (JAB) Removing Snts
// August 25, 2006: (JAB) Branching for Cedar and
//                         setting fTitle
// July 20, 2006: (JAB) Branched to run with R1-24
// July  3, 2006: (JAB) Modified to Use DataQualityReader (AB code)

// Usage
// cp <path>/reco_near_spill_cedar.C reco_spill.C
// loon -bq "reco_spill.C()" <data_file>

/////////////////////////////////////////////////////////
// Description of this                                 //
// This file will produce a Spill stream (events that  //
//  make it through the spill trigger). This is        //
//  only meant to do NearDet processing in Cedar.      //
//  Processing occurs through a single path "Spill"    //
//  No filtering applied outside of finding the spills //
//  Each output stream requires its own processing     //
//   branch and so there are small offshoot branches   //
// Uses: CandSubShower Module                          //
//       CandEventSR (modified to use SS)              //
//       CandTrackCam                                  //
//       CandFitTrackCam                               //
//       GeoGeometry (in reco)                         //
//                                                     //
// Output:                                             //
// This file produces BeamNtp Information in each      //
//   output stream                                     //
// 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 SetMSGLevels(JobC &jc);

void reco_spill()
{
  reco_near_spill_cedar();
}

void reco_near_spill_cedar()
{
  LoadLibraries();

  JobC jc;
  
  jc.Path.Create("Spill",
                 "DataQualityReader::Reco "
		 "RecordSetupModule::Get "
                 "NeardetBeamSelect::Ana "
		 "DigitListModule::Get "
		 "DigitListModule::Reco "
                 "FilterDigitListModule::Reco "
		 "StripSRListModule::Reco "
		 "SliceSRListModule::Reco "
		 "TrackCamListModule::Reco "
		 "FitTrackCamListModule::Reco "
		 "ClusterSRListModule::Reco "
                 "SubShowerSRListModule::Reco "
		 "ShowerSRListModule::Reco "
		 "EventSRListModule::Reco "
		 "RecordSetupModule::Reco "
                 "NtpBDLite::Reco "
		 );

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

  //turn off all filters
  jc.Path("Spill").SetAllFilters(0);
  jc.Path("Spill").Node("NeardetBeamSelect::Ana").FilterOn();

  jc.Path("Spill").Mod("DataQualityReader").Set("FilterOnOff=1");
  jc.Path("Spill").Node("DataQualityReader::Reco").FilterOn();

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

  //Setting modifications for neardet-PhotonTransport
  //explicitly set the value of GeVPerMip

  jc.Path("Spill").Mod("SliceSRListModule").Set("SliceListAlgConfig=NearBeam");
  jc.Path("Spill").Mod("ClusterSRListModule").Set("ClusterListAlgConfig=NearBeam");
  jc.Path("Spill").Mod("FitTrackCamListModule").Set("NameListIn=CandTrackSRList"); 

  jc.Path("Spill").Mod("TrackCamListModule").Set("TrackListAlgConfig=default");
  jc.Path("Spill").Mod("TrackCamListModule").Set("NameListIn=CandSliceList");
  jc.Path("Spill").Mod("TrackCamListModule").Set("NameListOut=CandTrackSRList");                                                                                
  jc.Path("Spill").Mod("EventSRListModule").Set("EventListAlgorithm=AlgEventSSList");
  jc.Path("Spill").Mod("EventSRListModule").Set("EventListAlgConfig=NearBeam");

  //Set up the conditions for the CandSubShower Package
  jc.Path("Spill").Mod("SubShowerSRListModule").Set("SubShowerSRListAlgConfig=default");
  jc.Path("Spill").Mod("ShowerSRListModule").Set("ShowerListAlgorithm=AlgShowerSSList");
  jc.Path("Spill").Mod("ShowerSRListModule").Set("ShowerListAlgConfig=default");
  jc.Path("Spill").Mod("ShowerSRListModule").Set("ListOut=CandShowerSRList");
	
  jc.Path("Spill").Mod("StripSRListModule").Set("ListIn=canddigitlist");
  jc.Path("Spill").Mod("DigitListModule").Set("ListsToMake=1");    //Write both canddigitlist and candmcdigitlist.
  jc.Path("Spill").Mod("FilterDigitListModule").Set("FilterDigitListAlgorithm=AlgFilterDigitList");
  jc.Path("Spill").Mod("FilterDigitListModule").Set("FilterDigitListAlgConfig=NearDet");
  jc.Path("Spill").Mod("FilterDigitListModule").Set("SwitchPersToTemp=1"); //

  //////////////////////////////////////
    
  // 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("Spill").Mod("FilterDigitListModule").Report();
  jc.Path("Spill").Mod("StripSRListModule").Report();
  jc.Path("Spill").Mod("ShowerSRListModule").Report();
  jc.Path("Spill").Mod("TrackCamListModule").Report();
  jc.Path("Spill").Mod("FitTrackCamListModule").Report();
  jc.Path("Spill").Mod("SubShowerSRListModule").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)
  jc.Path.Create("CandOut", 
		 "Output::Put "
                 );
  SetCandOutputWithBNtp(jc.Path("CandOut").Mod("Output"), "CandS.root");
  jc.Path.Attach("Spill", "CandOut");

  //Ntuple record has its own output file so needs its own output module
  jc.Path.Create("NtpSR",
                 "NtpStModule::Get "
                 "NtpSRModule::Reco "
		 "Output::Put "
		 );
  jc.Path("NtpSR").Mod("NtpSRModule").Set("UseStandard=1"); // use NtpSt

  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(minossoft:%s,root:%s)", BaseRel, RootVer.c_str());
                                                                                
  jc.Path("NtpSR").Mod("NtpStModule").Set(RecTitle);


  SetNtpStOutputWithBNtp(jc.Path("NtpSR").Mod("Output"), "ntupleStS.root");
  jc.Path.Attach("Spill","NtpSR");

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

  SetMSGLevels(jc);

  //Other Run Options
  //  jc.Path("All").Run(100);  //Run over the first 100 snarls
  //  jc.Input.Next(10);  //Skip 10 Snarls 
  jc.Path("Spill").Run();
  jc.Path("Spill").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("libBeamDataNtuple");
  gSystem->Load("libBeamDataAnaSummary.so");
  gSystem->Load("libBeamDataUtil.so");

  gSystem->Load("libSpillTiming.so");
  gSystem->Load("libCandShield");
  gSystem->Load("libAltDeMux");
  gSystem->Load("libFiltration");
}

void SetCalibrator()
{
  Calibrator& cal = Calibrator::Instance();
     cal.Set("TimeCalibrator", "PulserTimeCalScheme");
     cal.Set("PeCalibrator",   "PEGainCalScheme");
     cal.Set("VALinCalibrator","SimpleCalScheme");
     cal.Set("DriftCalibrator","MuonDriftCalScheme");
     cal.Set("LinCalibrator",  "QuadLinearityCalScheme");
     cal.Set("StripCalibrator","StripToStripCalScheme");
     cal.Set("AttenCalibrator","StripAttenCalScheme");
     cal.Set("MIPCalibrator",  "MIPCalScheme");
     cal.Set("Thermometer",    "TemperatureCalScheme");
                                                                                
     // Sets it to use Andy Blake's timing constants
     //    the alternative being Brians
     Calibrator::TimeCalibrator().Set("MuonTask=Andys");
     //This turns on Andy Blakes time-walk correction
     Calibrator::TimeCalibrator().Set("DoWalkCorrection=1");
     //This turns on time jump table which corrects for hardware swaps
     //  through Fall 2004. (AB)
     Calibrator::TimeCalibrator().Set("UseJumps=1");
     //Turns on the automatic LI timewalk correction
     Calibrator::TimeCalibrator().Set("UsePulserCalibration=0");
}

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 SetMSGLevels(JobC &jc){
  //Configure the message service
  jc.Msg.SetLevel("FitTrackCamListModule","Error");
  jc.Msg.SetLevel("Cand","Error");
  jc.Msg.SetLevel("Calibrator","Fatal");
  jc.Msg.SetLevel("Dbi","Fatal");
  jc.Msg.SetLevel("Plex","Error");
  jc.Msg.SetLevel("AlgShowerSS", "Warning");
  jc.Msg.SetLevel("SubShowerSR","Error");
  jc.Msg.SetLevel("AlgFitTrackSR","Warning");  

  jc.Msg.SetLevel("DataQuality", "Warning");

}
