/* ======================================================================== *\
!
! *
! * 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
!
!
\* ======================================================================== */

const TString defpath = "/mnt/Data/rootdata/CrabNebula/2004_01_27/";
const TString defrout = "output_test.root";

const Int_t defpedr [] = {12461};
const Int_t defcalr [] = {12526,12527,12528,12529};
const Int_t defdatar[] = {12517,12518};

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

{

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

  MCalibrationCam::PulserColor_t color;

  if (calruns[0] < 20000)
    color = MCalibrationCam::kCT1;
  else
    color = FindColor((MDirIter*)&cruns);

  if (color == MCalibrationCam::kNONE)
    {
      TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
      
      while (1)
        {
          timer.TurnOn();
          TString input = Getline("Could not find the correct colour: Type 'q' to exit, "
                                  "green, blue, uv or ct1 to go on: ");
          timer.TurnOff();
          
          if (input=="q\n")
            return ;
          
          if (input=="green")
            color = MCalibrationCam::kGREEN;
          if (input=="blue")
            color = MCalibrationCam::kBLUE;
          if (input=="uv")
            color = MCalibrationCam::kUV;
          if (input=="ct1")
            color = MCalibrationCam::kCT1;
        }
    }

  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:
  // ---------------------------------------------------
  //
  MCalibrationQECam qecam;
  MJCalibration     calloop;
  calloop.SetColor(color);
  calloop.SetInput(&cruns);
  //  calloop.SetFullDisplay();
  //
  // Use as signal extractor MExtractSignal2:
  //
  calloop.SetExtractorLevel(2);
  //
  // Set the corr. cams:
  //
  calloop.SetQECam(qecam);
  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;
  
  MBadPixelsCam          &badbad  = calloop.GetBadPixels();
  MCalibrationChargeCam  &calcam  = calloop.GetCalibrationCam();
  MCalibrationRelTimeCam &timecam = calloop.GetRelTimeCam();

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

  MExtractSignal2     sigcalc;
  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(&sigcalc);
  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();

}

void CamDraw(TCanvas &c, MHCamera &cam, MCamEvent &evt, Int_t i, Int_t j, Int_t fit)
{

  c.cd(i);
  gPad->SetBorderMode(0);
  MHCamera *obj1=(MHCamera*)cam.DrawCopy("hist");
  //  obj1->AddNotify(evt);
  
  c.cd(i+j);
  gPad->SetBorderMode(0);
  obj1->Draw();
  ((MHCamera*)obj1)->SetPrettyPalette();

  if (fit != 0)
    {
      c.cd(i+2*j);
      gPad->SetBorderMode(0);
      TH1D *obj2 = (TH1D*)obj1->Projection(obj1.GetName());
      
//      obj2->Sumw2();
      obj2->Draw();
      obj2->SetBit(kCanDelete);

      const Double_t min   = obj2->GetBinCenter(obj2->GetXaxis()->GetFirst());
      const Double_t max   = obj2->GetBinCenter(obj2->GetXaxis()->GetLast());
      const Double_t integ = obj2->Integral("width")/2.5066283;
      const Double_t mean  = obj2->GetMean();
      const Double_t rms   = obj2->GetRMS();
      const Double_t width = max-min;

      if (rms == 0. || width == 0. )
        return;
      
      switch (fit)
        {
        case 1:
          TF1 *sgaus = new TF1("sgaus","gaus(0)",min,max);
          sgaus->SetBit(kCanDelete);
          sgaus->SetParNames("Area","#mu","#sigma");
          sgaus->SetParameters(integ/rms,mean,rms);
          sgaus->SetParLimits(0,0.,integ);
          sgaus->SetParLimits(1,min,max);
          sgaus->SetParLimits(2,0,width/1.5);
          obj2->Fit("sgaus","QLR");
          obj2->GetFunction("sgaus")->SetLineColor(kYellow);
          break;

        case 2:
          TString dgausform = "([0]-[3])/[2]*exp(-0.5*(x-[1])*(x-[1])/[2]/[2])";
          dgausform += "+[3]/[5]*exp(-0.5*(x-[4])*(x-[4])/[5]/[5])";
          TF1 *dgaus = new TF1("dgaus",dgausform.Data(),min,max);
          dgaus->SetBit(kCanDelete);
          dgaus->SetParNames("A_{tot}","#mu_{1}","#sigma_{1}","A_{2}","#mu_{2}","#sigma_{2}");
          dgaus->SetParameters(integ,(min+mean)/2.,width/4.,
                               integ/width/2.,(max+mean)/2.,width/4.);
          // The left-sided Gauss 
          dgaus->SetParLimits(0,integ-1.5,integ+1.5);
          dgaus->SetParLimits(1,min+(width/10.),mean);
          dgaus->SetParLimits(2,0,width/2.);
          // The right-sided Gauss 
          dgaus->SetParLimits(3,0,integ);
          dgaus->SetParLimits(4,mean,max-(width/10.));
          dgaus->SetParLimits(5,0,width/2.);
          obj2->Fit("dgaus","QLRM");
          obj2->GetFunction("dgaus")->SetLineColor(kYellow);
          break;
          
        case 3:
          TString tgausform = "([0]-[3]-[6])/[2]*exp(-0.5*(x-[1])*(x-[1])/[2]/[2])";
          tgausform += "+[3]/[5]*exp(-0.5*(x-[4])*(x-[4])/[5]/[5])";
          tgausform += "+[6]/[8]*exp(-0.5*(x-[7])*(x-[7])/[8]/[8])";
          TF1 *tgaus = new TF1("tgaus",tgausform.Data(),min,max);
          tgaus->SetBit(kCanDelete);
          tgaus->SetParNames("A_{tot}","#mu_{1}","#sigma_{1}",
                             "A_{2}","#mu_{2}","#sigma_{2}",
                             "A_{3}","#mu_{3}","#sigma_{3}");
          tgaus->SetParameters(integ,(min+mean)/2,width/4.,
                               integ/width/3.,(max+mean)/2.,width/4.,
                               integ/width/3.,mean,width/2.);
          // The left-sided Gauss 
          tgaus->SetParLimits(0,integ-1.5,integ+1.5);
          tgaus->SetParLimits(1,min+(width/10.),mean);
          tgaus->SetParLimits(2,width/15.,width/2.);
          // The right-sided Gauss 
          tgaus->SetParLimits(3,0.,integ);
          tgaus->SetParLimits(4,mean,max-(width/10.));
          tgaus->SetParLimits(5,width/15.,width/2.);
          // The Gauss describing the outliers
          tgaus->SetParLimits(6,0.,integ);
          tgaus->SetParLimits(7,min,max);
          tgaus->SetParLimits(8,width/4.,width/1.5);
          obj2->Fit("tgaus","QLRM");
          obj2->GetFunction("tgaus")->SetLineColor(kYellow);
          break;
        case 4:
          obj2->Fit("pol0","Q");
          obj2->GetFunction("pol0")->SetLineColor(kYellow);
          break;
        case 9:
          break;
        default:
          obj2->Fit("gaus","Q");
          obj2->GetFunction("gaus")->SetLineColor(kYellow);
          break;
        }
      
        TArrayI s0(3);
        s0[0] = 6;
        s0[1] = 1;
        s0[2] = 2;

        TArrayI s1(3);
        s1[0] = 3;
        s1[1] = 4;
        s1[2] = 5;

        TArrayI inner(1);
        inner[0] = 0;

        TArrayI outer(1);
        outer[0] = 1;

        // Just to get the right (maximum) binning
        TH1D *half[4];
        half[0] = obj1->ProjectionS(s0, inner, "Sector 6-1-2 Inner");
        half[1] = obj1->ProjectionS(s1, inner, "Sector 3-4-5 Inner");
        half[2] = obj1->ProjectionS(s0, outer, "Sector 6-1-2 Outer");
        half[3] = obj1->ProjectionS(s1, outer, "Sector 3-4-5 Outer");

        for (int i=0; i<4; i++)      
        {
            half[i]->SetLineColor(kRed+i);
            half[i]->SetDirectory(0);
            half[i]->SetBit(kCanDelete);
            half[i]->Draw("same");
        }

      gPad->Modified();
      gPad->Update();
      
    }
}


MCalibrationCam::PulserColor_t FindColor(MDirIter* run) 
{
  
  MCalibrationCam::PulserColor_t col = MCalibrationCam::kNONE;

  TString filenames;

  while (!(filenames=run->Next()).IsNull())
    {

      filenames.ToLower();

      if (filenames.Contains("green"))
        if (col == MCalibrationCam::kNONE)
          {
            cout << "Found colour: Green  in " << filenames << endl;
            col = MCalibrationCam::kGREEN;
          }
        else if (col != MCalibrationCam::kGREEN)
          {
            cout << "Different colour found in " << filenames << "... abort" << endl;
            return MCalibrationCam::kNONE;
          }

      if (filenames.Contains("blue"))
        if (col == MCalibrationCam::kNONE)
          {
            cout << "Found colour: Blue  in " << filenames << endl;
            col = MCalibrationCam::kBLUE;
          }
        else if (col != MCalibrationCam::kBLUE)
          {
            cout << "Different colour found in " << filenames << "... abort" << endl;
            return MCalibrationCam::kNONE;
          }

      if (filenames.Contains("uv"))
        if (col == MCalibrationCam::kNONE)
          {
            cout << "Found colour: Uv  in " << filenames << endl;
            col = MCalibrationCam::kUV;
          }
        else if (col != MCalibrationCam::kUV)
          {
            cout << "Different colour found in " << filenames << "... abort" << endl;
            return MCalibrationCam::kNONE;
          }

      if (filenames.Contains("ct1"))
        if (col == MCalibrationCam::kNONE)
          {
            cout << "Found colour: Ct1  in " << filenames << endl;
            col = MCalibrationCam::kCT1;
          }
        else if (col != MCalibrationCam::kCT1)
          {
            cout << "Different colour found in " << filenames << "... abort" << endl;
            return MCalibrationCam::kNONE;
          }
      
    }
  

      
  if (col == MCalibrationCam::kNONE)
    cout <<  "No colour found in filenames of runs: " << ((MRunIter*)run)->GetRunsAsString() 
         << "... abort" << endl;
  
  return col;      
}
