/* ======================================================================== *\
!
! *
! * This file is part of MARS, the MAGIC Analysis and Reconstruction
! * Software. It is distributed to you in the hope that it can be a useful
! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
! * It is distributed WITHOUT ANY WARRANTY.
! *
! * Permission to use, copy, modify and distribute this software and its
! * documentation for any purpose is hereby granted without fee,
! * provided that the above copyright notice appear in all copies and
! * that both that copyright notice and this permission notice appear
! * in supporting documentation. It is provided "as is" without express
! * or implied warranty.
! *
!
!
!   Author(s): Hendrik Bartko, 03/2004 <mailto:hbartko@mppmu.mpg.de>
!              Markus Gaug,    03/2004 <mailto:markus@ifae.es>
!
!   Copyright: MAGIC Software Development, 2000-2004
!
!
\* ======================================================================== */

///////////////////////////////////////////////////////////////////////////
//
//   production.C
//   ============
//
//   This macro takes calibration runs and pedestal runs
//   to set pedestals and calibration factors
//   Then raw data files are read and calibrated.
//   The output file contains the calibrated data, pedestal subtracted,
//   with the signal (in photons) for each pixels
//
//   input:  calibration file(s)
//           pedestal file(s)
//           raw data files
//   
//   output: root files with following containers (branches)
//           - MCerPhotEvt
//           - MPedestalCam
//           - MCalibrationRelTimeCam
//           - MCerPhotEvt
//           - MRawEvtHeader
//           - MBadPixelsCam
//           - MPedPhotCam
//
///////////////////////////////////////////////////////////////////////////

//
// Set path for files and run numbers
//
const TString defpath = "/data1/earth/magic/data/Period014/rootdata/2004_02_15/";
const TString defrout = "output_Mrk421_20040215.root";

const Int_t defpedr [] = {17284};
const Int_t defcalr [] = {17285};
const Int_t defdatar[] = {17286,17287,17288,17289,17290,17291,17292,17293,
			  17294,17295,17296,17297,17298,17299,17300,17301,
			  17302,17303,17304,17305,17306,17307,17308,17309,
			  17310,17311,17312,17313,17314,17315,17316,17317,
			  17318,17319,17320,17321,17322,17323,17324,17325,
			  17326,17327,17328,17329,17330,17331,17332,17333,
			  17334,17335,17336,17337,17338,17339,17340,17341,
			  17342,17343,17344,17345,17346,17347,17348,17349,
			  17350,17351,17352,17353,17354,17355,17356,17357,
			  17358,17359,17360,17361,17362,17363,17364,17365,
			  17366,17367,17368,17369,17370,17371,17372,17373,
			  17374,17375,17376,17377,17378,17379,17380,17381,
			  17382,17383,17384,17385,17386,17387,17388,17389,
			  17390,17391,17392,17393,17394,17395,17396,17397,
			  17398,17399,17400,17401,17402,17403,17404,17405,
			  17406,17407,17408,17409,17410,17411,17412,17413,
			  17414,17415,17416,17417,17418,17419,17420,17421,
			  17422,17423,17424,17425,17426,17427,17428,17429,
			  17430,17431,17432,17433,17434,17435,17436,17437,
			  17438,17439,17440,17441,17442,17443,17444,17445,
			  17446,17447,17448,17449,17450,17451,17452,17453,
			  17454,17455,17456};


void production(const TString inpath=defpath, 
                    const Int_t psize=1, const Int_t pedruns[]=defpedr, 
                    const Int_t csize=1, const Int_t calruns[]=defcalr, 
                    const Int_t dsize=171, const Int_t dataruns[]=defdatar, 
                    const TString resname=defrout)

{

  MExtractSlidingWindow extractor;

  MRunIter pruns;
  MRunIter cruns;
  MRunIter druns;
  
  for (Int_t i=0;i<psize;i++) {
    cout << "Adding pedestal run: " << pedruns[i] << endl;
    pruns.AddRun(pedruns[i],inpath);
  }
  for (Int_t i=0;i<csize;i++) {
    cout << "Adding calibration run: " << calruns[i] << endl;
    cruns.AddRun(calruns[i],inpath);
  }
  for (Int_t i=0;i<dsize;i++) {
    cout << "Adding data run: " << dataruns[i] << endl;
    druns.AddRun(dataruns[i],inpath);
  }


  MStatusDisplay *display = new MStatusDisplay;
  display->SetUpdateTime(3000);
  display->Resize(850,700);

  gStyle->SetOptStat(1111);
  gStyle->SetOptFit();

  /************************************/
  /* FIRST LOOP: PEDESTAL COMPUTATION */
  /************************************/
  
  MParList plist1;
  MTaskList tlist1;
  plist1.AddToList(&tlist1);
  
  // containers
  MPedestalCam   pedcam;
  MBadPixelsCam  badcam;
  //
  // for excluding pixels from the beginning:
  //
  // badcam.AsciiRead("badpixels.dat");


  plist1.AddToList(&pedcam);
  plist1.AddToList(&badcam);
    
  //tasks
  MReadMarsFile  read("Events");
  read.DisableAutoScheme();
  static_cast<MRead&>(read).AddFiles(pruns);

  MGeomApply     geomapl;
  MPedCalcPedRun pedcalc;
  MGeomCamMagic  geomcam;
    
  tlist1.AddToList(&read);
  tlist1.AddToList(&geomapl);
  tlist1.AddToList(&pedcalc);

  // Create and execute the event looper
  MEvtLoop pedloop;
  pedloop.SetParList(&plist1);
  pedloop.SetDisplay(display);

  cout << "*************************" << endl;
  cout << "** COMPUTING PEDESTALS **" << endl;
  cout << "*************************" << endl;

  if (!pedloop.Eventloop())
    return;
  
  tlist1.PrintStatistics();

  // 
  // Now the short version: 
  //
  //
  // Now setup the new tasks for the calibration:
  // ---------------------------------------------------
  //
  MJCalibration     calloop;
  calloop.SetInput(&cruns);
  //  calloop.SetFullDisplay();
  //
  calloop.SetExtractor(&extractor);
  //
  // Set the corr. cams:
  //
  calloop.SetBadPixels(badcam);
  //
  // The next two commands are for the display:
  //
  calloop.SetDisplay(display);
  
  //
  // Apply rel. time calibration:
  //
  calloop.SetRelTimeCalibration();
  //
  // Use as arrival time extractor MArrivalTimeCalc2:
  //
  calloop.SetArrivalTimeLevel(2);
  
  //
  // Do the event-loop:
  //
  cout << "***************************" << endl;
  cout << "** COMPUTING CALIBRATION **" << endl;
  cout << "***************************" << endl;
  
  if (!calloop.Process(pedcam))
    return;

  badcam.Print();
  
  MBadPixelsCam          &badbad  = calloop.GetBadPixels();
  MCalibrationChargeCam  &calcam  = calloop.GetCalibrationCam();
  MCalibrationRelTimeCam &timecam = calloop.GetRelTimeCam();
  MCalibrationQECam      &qecam   = calloop.GetQECam();

  badbad.Print();

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

  // Create an empty Parameter List and an empty Task List
  MParList  plist3;  
  MTaskList tlist3;
  plist3.AddToList(&tlist3);
 
  // containers
  MCerPhotEvt         photevt;
  MPedPhotCam         pedphotcam;
  MSrcPosCam          srccam;
  MRawRunHeader       runhead;
  MExtractedSignalCam sigcam;

  plist3.AddToList(&geomcam );
  plist3.AddToList(&pedcam  );
  plist3.AddToList(&calcam  );
  plist3.AddToList(&qecam   );
  plist3.AddToList(&badbad  );
  plist3.AddToList(&timecam );
  plist3.AddToList(&sigcam  );
  plist3.AddToList(&photevt);
  plist3.AddToList(&pedphotcam);
  plist3.AddToList(&srccam);
  plist3.AddToList(&runhead);

  //tasks
  MReadMarsFile read3("Events");
  read3.DisableAutoScheme();
  static_cast<MRead&>(read3).AddFiles(druns);

  MArrivalTimeCalc2   timecalc;
  MCalibrateData      photcalc;     
  photcalc.SetCalibrationMode(MCalibrateData::kFfactor);  // !!! was only MCalibrate
  // MPedPhotCalc     pedphotcalc;   // already done by MCalibrate Data
  // MCerPhotCalc     cerphotcalc;  // already done by MCalibrate Data
  
  tlist3.AddToList(&read3);
  tlist3.AddToList(&geomapl);
  tlist3.AddToList(&extractor);
  tlist3.AddToList(&timecalc);
  //  tlist3.AddToList(&cerphotcalc); // already done by MCalibrate Data
  tlist3.AddToList(&photcalc);
  // tlist3.AddToList(&pedphotcalc);   // already done by MCalibrate Data

  MWriteRootFile write(resname);
  
  write.AddContainer("MGeomCam"              , "RunHeaders");
  write.AddContainer("MRawRunHeader"         , "RunHeaders");
  write.AddContainer("MSrcPosCam"            , "RunHeaders");
  write.AddContainer("MCalibrationChargeCam" , "RunHeaders");
  write.AddContainer("MCalibrationQECam"     , "RunHeaders");
  //  write.AddContainer("MPedPhotCam","RunHeaders"); // Attention, was in Events - Tree!!
  write.AddContainer("MPedestalCam"          , "RunHeaders");
  write.AddContainer("MCalibrationRelTimeCam", "RunHeaders");

  write.AddContainer("MCerPhotEvt"   , "Events");
  write.AddContainer("MRawEvtHeader" , "Events");
  write.AddContainer("MBadPixelsCam" , "Events");
  write.AddContainer("MPedPhotCam"   , "Events");

  tlist3.AddToList(&write);
  
  // Create and execute eventloop
  MEvtLoop evtloop3;
  evtloop3.SetParList(&plist3);
    
  cout << "*************************************************************" << endl;
  cout << "***   COMPUTING DATA USING EXTRACTED SIGNAL (IN PHOTONS)  ***" << endl;
  cout << "*************************************************************" << endl;
  
  if (!evtloop3.Eventloop())  
    return;  
  tlist3.PrintStatistics();

}



