/*********************************/
/* Compute the hillas parameters */
/*********************************/

#include "TString.h"
#include "TArrayS.h"

#include "MParList.h"
#include "MTaskList.h"
#include "MPedestalCam.h"
#include "MBadPixelsCam.h"
#include "MReadMarsFile.h"
#include "MGeomApply.h"
#include "MPedCalcPedRun.h"
#include "MEvtLoop.h"
#include "MGeomCamMagic.h"
#include "MExtractedSignalCam.h"
#include "MCalibrationChargeCam.h"
#include "MHCalibrationChargeCam.h"
#include "MHCalibrationRelTimeCam.h"
#include "MExtractor.h"
#include "MExtractFixedWindow.h"
#include "MExtractSignal.h"
#include "MCalibrationChargeCalc.h"
#include "MFCosmics.h"
#include "MContinue.h"
#include "MLog.h"
#include "MCerPhotEvt.h"
#include "MPedPhotCam.h"
#include "MCalibrate.h"
#include "MPedPhotCalc.h"
#include "MHillas.h"
#include "MNewImagePar.h"
#include "MRawRunHeader.h"
#include "MSrcPosCam.h"
#include "MBlindPixelCalc.h"
#include "MImgCleanStd.h"
#include "MHillasSrcCalc.h"
#include "MHillasCalc.h"
#include "MArrivalTimeCam.h"
#include "MArrivalTimeCalc2.h"
#include "MIslands.h"
#include "MIslandCalc.h"
#include "MIslandClean.h"
#include "MWriteRootFile.h"
#include "MArgs.h"
#include "MRunIter.h"
#include "MJPedestal.h"
#include "MJCalibration.h"
#include "MHillasDisplay.h"
#include "MF.h"
#include "MContinue.h"

#include "TApplication.h"

#include <iostream>
#include <fstream>
#include <stdlib.h>

using namespace std;

Bool_t readDatacards(TString& filename);
void makeHillas();

// initial and final time slices to be used in signal extraction
const Byte_t hifirst = 0;
const Byte_t hilast  = 13;
const Byte_t lofirst = 3;
const Byte_t lolast  = 12;

// declaration of variables read from datacards
TString  outname;
TString  idirname;
TString  filter;
TString  psfilename("makehillas.ps");
MRunIter caliter;
MRunIter pediter;
MRunIter datiter;
UInt_t   display   = 0;
ULong_t  nmaxevents= 999999999;
Short_t  calflag   = 1;
Float_t  lcore     = 3.0;
Float_t  ltail     = 1.5;
Int_t    islflag   = 0;
Float_t  lnew      = 40;
Int_t    kmethod   = 1;
Int_t    nfiles    = 0;

const TString defaultcard="makehillas.datacard";
/*************************************************************/
static void Usage()
{
  gLog <<endl;
  gLog << "Usage is:" << endl;
  gLog << "   makeHillas [-h] [-?] <datacards>" << endl << endl;
  gLog << "     <datacards>: datacards file name (dafault input.datacards)" << endl;
  gLog << "     -?/-h: This help" << endl << endl;
}
/*************************************************************/
int main(int argc, char **argv)
{
  // create a TApplication to be able to 
  TApplication app("Application",0,0);

  // evaluate arguments
  MArgs arg(argc, argv);
  if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
    {
      Usage();
      return -1;
    }

  TString datacard  = arg.GetArgumentStr(0);
  if(!datacard.Length())
    datacard = defaultcard;

  if(!readDatacards(datacard))
    {
      cout << "Error reading datacards. Stoping" << endl;
      return -1;
    }
  makeHillas();
}

/*************************************************************/
void makeHillas()
{
  // Set the general tasks/containers
  MExtractFixedWindow    extractor;
  extractor.SetRange(hifirst,hilast,lofirst,lolast);

  //  MCalibrationQECam   qecam;
  //  MBadPixelsCam       badcam;
  MGeomCamMagic       geomcam;
  MGeomApply          geomapl;

  /************************************/
  /* FIRST LOOP: PEDESTAL COMPUTATION */
  /************************************/

  // If you want to exclude pixels from the beginning, read 
  // an ascii-file with the corr. pixel numbers (see MBadPixelsCam)  
  //badcam.AsciiRead("badpixels.dat");

  MJPedestal pedloop;
  pedloop.SetInput(&pediter);
  pedloop.SetExtractor(&extractor);
  //  pedloop.SetBadPixels(badcam);

  if (!pedloop.Process())
    return;

  /*****************************/
  /* SECOND LOOP: CALIBRATION  */
  /*****************************/        

  MJCalibration calloop;

  calloop.SetExtractor(&extractor);
  calloop.SetInput(&caliter);
  //  calloop.SetQECam(qecam);
  calloop.SetBadPixels(pedloop.GetBadPixels());

  if(calflag>0)
    if (!calloop.Process(pedloop.GetPedestalCam()))
      return;


  /************************************************************************/
  /*                THIRD LOOP: PEDESTAL CALIBRATION INTO PHOTONS         */
  /************************************************************************/
  MParList  plist3;
  MTaskList tlist3;
  plist3.AddToList(&tlist3);
  
  // containers
  MCerPhotEvt         nphot;
  MPedPhotCam         nphotrms;
  MExtractedSignalCam sigcam;

  plist3.AddToList(&geomcam);
  plist3.AddToList(&pedloop.GetPedestalCam());
  plist3.AddToList(&calloop.GetCalibrationCam());
  plist3.AddToList(&calloop.GetQECam());
  plist3.AddToList(&calloop.GetRelTimeCam());
  //  plist3.AddToList(&badcam);
  plist3.AddToList(&sigcam);
  plist3.AddToList(&nphot);
  plist3.AddToList(&nphotrms);

  
  MCalibrate::CalibrationMode_t calMode=MCalibrate::kDefault;  
  if(calflag==0)
    calMode=MCalibrate::kNone;
  if(calflag==-1)
    calMode=MCalibrate::kDummy;

  //tasks
  MReadMarsFile read3("Events");
  static_cast<MRead&>(read3).AddFiles(pediter); 
  read3.DisableAutoScheme();
 
  //  MExtractSignal  extsig;
  //  extsig.SetRange(hifirst,hilast,lofirst,lolast);
  MCalibrate      photcalc(calMode);
  MPedPhotCalc    photrmscalc; 
  
  tlist3.AddToList(&read3);
  tlist3.AddToList(&geomapl);
  tlist3.AddToList(&extractor);
  tlist3.AddToList(&photcalc);
  tlist3.AddToList(&photrmscalc);

  // Create and setup the eventloop
  MEvtLoop evtloop3;
  evtloop3.SetParList(&plist3);
  if (!evtloop3.Eventloop())
    return;
  
  tlist3.PrintStatistics();

  /************************************************************************/
  /*                FOURTH LOOP: DATA CALIBRATION INTO PHOTONS            */
  /************************************************************************/

  MParList  plist4;
  MTaskList tlist4;
  plist4.AddToList(&tlist4);
  
  // containers 
  MHillas       hillas;
  MNewImagePar  newimagepar;
  MSrcPosCam    source;
  MRawRunHeader runhead;

  MArrivalTimeCam   timecam;
     
  MIslands      isl;
  isl.SetName("MIslands1");
  
  MIslands      isl2;
  isl2.SetName("MIslands2");

  if (islflag == 1 || islflag == 2)
    {
      plist4.AddToList(&timecam);
      plist4.AddToList(&isl);
    }
  
  if (islflag == 2)
    {
      plist4.AddToList(&isl2);
    }
  
  plist4.AddToList(&geomcam);
  plist4.AddToList(&pedloop.GetPedestalCam());
  plist4.AddToList(&calloop.GetCalibrationCam());
  plist4.AddToList(&calloop.GetQECam());
  plist4.AddToList(&calloop.GetRelTimeCam());
  //  plist4.AddToList(&badcam);
  plist4.AddToList(&nphot);
  plist4.AddToList(&nphotrms);
  plist4.AddToList(&source);
  plist4.AddToList(&hillas);
  plist4.AddToList(&newimagepar);
  plist4.AddToList(&runhead);

  // cuts
  MF cut(filter);
  
  //tasks
  MReadMarsFile read4("Events");
  static_cast<MRead&>(read4).AddFiles(datiter); 
  read4.DisableAutoScheme();
  
  // set bad pixels 
  MBlindPixelCalc   blind;
  MBlindPixelCalc   blind2;
  const Short_t x[16] = {330,395,329,396,389,
                         323,388,322,384,385,
                         386,387,321,320,319,
                         394};
  const TArrayS bp(16,(Short_t*)x);
  blind.SetPixelIndices(bp);
  blind2.SetPixelIndices(bp);
  
  MImgCleanStd      clean(lcore,ltail);

  MArrivalTimeCalc2 timecalc;
  
  MIslandCalc       island;
  island.SetOutputName("MIslands1");

  MIslandClean      islclean(lnew);
  islclean.SetInputName("MIslands1");
  islclean.SetMethod(kmethod);
      
  MIslandCalc       island2;
  island2.SetOutputName("MIslands2");  
  
  
  MHillasCalc       hcalc;
  MHillasSrcCalc    csrc1;
  
  MContinue applycut(&cut);
  applycut.SetInverted(kTRUE);
  MWriteRootFile* write=NULL;
  MHillasDisplay*  disphillas=NULL;

  write = new MWriteRootFile(outname,"RECREATE");
  
  write->AddContainer("MHillas"        , "Parameters");
  write->AddContainer("MHillasSrc"     , "Parameters");
  write->AddContainer("MHillasExt"     , "Parameters");
  write->AddContainer("MNewImagePar"   , "Parameters");
  write->AddContainer("MRawEvtHeader"  , "Parameters");
  write->AddContainer("MRawRunHeader"  , "Parameters");
  write->AddContainer("MConcentration" , "Parameters");
  write->AddContainer("MSrcPosCam"     , "Parameters");
  
  if (islflag == 1 || islflag == 2)
    write->AddContainer("MIslands1" , "Parameters");
  if (islflag == 2) 
    write->AddContainer("MIslands2" , "Parameters");

  if(display)
    {
      disphillas = new MHillasDisplay(&nphot,&geomcam);
      if (islflag == 1)
	disphillas->SetIslandsName("MIslands1");
      if (islflag == 2)
	disphillas->SetIslandsName("MIslands2");

    }      

  tlist4.AddToList(&read4);
  tlist4.AddToList(&geomapl);
  tlist4.AddToList(&extractor);
  tlist4.AddToList(&photcalc);
  //tlist4.AddToList(&blind);
  tlist4.AddToList(&clean);

  if (islflag == 1 || islflag == 2)
    {
      tlist4.AddToList(&timecalc);
      tlist4.AddToList(&island);
    }

  if (islflag == 2)
    {
      tlist4.AddToList(&islclean);
      tlist4.AddToList(&island2);
    }
  
  //tlist4.AddToList(&blind2);
  tlist4.AddToList(&hcalc);
  tlist4.AddToList(&csrc1);
  if(filter.Length())
    tlist4.AddToList(&applycut);
  tlist4.AddToList(write);
  if(display)
    {
      disphillas->SetPSFile();
      disphillas->SetPSFileName(psfilename);
      if(display==2) 
	disphillas->SetPause(kFALSE);	
      tlist4.AddToList(disphillas);
    }


  // Create and setup the eventloop
  MEvtLoop datloop;
  datloop.SetParList(&plist4);

  cout << "*************************************************************" << endl;
  cout << "***   COMPUTING DATA USING EXTRACTED SIGNAL (IN PHOTONS)  ***" << endl;
  cout << "*************************************************************" << endl;
  
  if (!datloop.Eventloop(nmaxevents))
    return;

  tlist4.PrintStatistics();    

}
//-------------------------------------------------------------------------------

Bool_t readDatacards(TString& filename)
{
  ifstream ifun(filename.Data());
  if(!ifun)
    {
      cout << "File " << filename << " not found" << endl;
      return kFALSE;
    }

  TString word;
  
  while(ifun >> word)
    {
      // skip comments
      if(word[0]=='/' && word[1]=='/')
	{
	  while(ifun.get()!='\n'); // skip line
	  continue;
	}

      // number of events
      if(strcmp(word.Data(),"NEVENTS")==0)
	ifun >> nmaxevents;


      // input file directory
      if(strcmp(word.Data(),"IDIR")==0)
	{
	  if(idirname.Length())
	    cout << "readDataCards Warning: overriding input directory file name" << endl;
	  ifun >> idirname;
	}

      // pedestal runs
      if(strcmp(word.Data(),"PRUNS")==0)
	{
	  if(pediter.GetNumRuns())
	    cout << "readDataCards Warning: adding pedestal runs to the existing list" << endl;
	  ifun >> word;
	  pediter.AddRuns(word.Data(),idirname.Data());
	}

      // calibration runs
      if(strcmp(word.Data(),"CRUNS")==0)
	{
	  if(caliter.GetNumRuns())
	    cout << "readDataCards Warning: adding calibration runs to the existing list" << endl;
	  ifun >> word;
	  caliter.AddRuns(word.Data(),idirname.Data());
	}

      // data runs
      if(strcmp(word.Data(),"DRUNS")==0)
	{
	  if(datiter.GetNumRuns())
	    cout << "readDataCards Warning: adding data runs to the existing list" << endl;
	  ifun >> word;
	  datiter.AddRuns(word.Data(),idirname.Data());
	}
      
      // output file name
      if(strcmp(word.Data(),"OUTFILE")==0)
	{
	  if(outname.Length())
	    cout << "readDataCards Warning: overriding output file name" << endl;
	  ifun >> outname;
	}

      // exclusion cut
      if(strcmp(word.Data(),"FILTER")==0)
	{
	  if(filter.Length())
	    cout << "readDataCards Warning: overriding existing cut" << endl;
	  
	  char ch;
	  while((ch=ifun.get())!='\n')
	    filter.Append(ch);	  
	}

      // display flag
      if(strcmp(word.Data(),"DISPLAY")==0)
	ifun >> display;

      // ps file name
      if(strcmp(word.Data(),"PSFILENAME")==0)
	ifun >> psfilename;

      // calibration flag
      if(strcmp(word.Data(),"CALFLAG")==0)
	ifun >> calflag;


      // cleaning level
      if(strcmp(word.Data(),"CLEANLEVEL")==0)
	{
	  ifun >> lcore;
	  ifun >> ltail;
	}

      if(strcmp(word.Data(),"ISLFLAG")==0)
	{
	  ifun >> islflag;
	}

      // island cleaning 
      if (islflag == 2){
	if(strcmp(word.Data(),"ISLANDCLEAN")==0)
	  {
	    ifun >> kmethod;
	    ifun >> lnew;
	  }
      }
    }

  pediter.Reset();
  caliter.Reset();
  datiter.Reset();
  TString pfile;

  // Dump read values
  cout << "************************************************" << endl;
  cout << "* Datacards read from file " << filename << endl;
  cout << "************************************************" << endl;
  cout << "Pedestal file (s): "  << endl;
  while(!(pfile=pediter.Next()).IsNull())
    cout << pfile << endl;
  cout << "Calibration file (s): "  << endl;
  while(!(pfile=caliter.Next()).IsNull())
    cout << pfile << endl;
  cout << "Data file (s): "  << endl;
  while(!(pfile=datiter.Next()).IsNull())
    cout << pfile << endl;
  cout << "Maximum number of events: " << nmaxevents << endl;
  if(filter.Length())
    cout << "Applying rejection cut: " << filter << endl;
  cout << "Output file name: " << outname << endl;
  if(display)
    cout << "Generating PS file: " << psfilename << endl;
  cout << "Calibration flag: " << calflag << endl;
  cout << "Cleaning level: ("<<lcore<<","<<ltail<<")" << endl;
  if (islflag == 1 || islflag == 2)
    cout << "Island calcultation..." << endl;
  if (islflag == 2)
    {
      cout << "Island Cleaning: "<< kmethod <<" method  "<< lnew << " new threshold" << endl;
    }
  cout << "***********" << endl << endl;
  
  if(!pediter.GetNumEntries())
    {
      cout << "No pedestal file name specified" << endl;
      return kFALSE;
    }
  if(!caliter.GetNumEntries() && calflag>0)
    {
      cout << "No calibration file name specified" << endl;
      return kFALSE;
    }
  if(!datiter.GetNumEntries())
    {
      cout << "No data file name specified" << endl;
      return kFALSE;
    }
  if(!outname.Length())
    {
      cout << "No output file name specified" << endl;
      return kFALSE;
    }


  return kTRUE;
}

