/* ======================================================================== *\
!
! *
! * 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): Javier Lopez 12/2003 <mailto:jlopez@ifae.es>
!
!   Copyright: MAGIC Software Development, 2000-2001
!
!
\* ======================================================================== */

//////////////////////////////////////////////////////////////////////////////
//
//   MCalibrate
//
//   This task takes the integrated charge from MExtractedSignal and apply
//   the calibration constants from MCalibraitionCam to the charge. Then
//   stores number of photons obtained in MCerPhotEvt.
//
//   Input Containers:
//    MExtractedSingal
//    MCalibrationCam
//
//   Output Containers:
//    MCerPhotEvt
//
//////////////////////////////////////////////////////////////////////////////
#include "MCalibrate.h"
#include "MCalibrationConfig.h"

#include <TMath.h>

#include "MLog.h"
#include "MLogManip.h"

#include "MParList.h"
#include "MH.h"

#include "MGeomCam.h"

#include "MCalibrationCam.h"
#include "MCalibrationPix.h"

#include "MExtractedSignalCam.h"
#include "MExtractedSignalPix.h"

#include "MCerPhotEvt.h"

ClassImp(MCalibrate);

using namespace std;
// --------------------------------------------------------------------------
//
// Default constructor. 
//
MCalibrate::MCalibrate(const char *name, const char *title)
{
    fName  = name  ? name  : "MCalibrate";
    fTitle = title ? title : "Task to calculate the number of photons in one event";
}

// --------------------------------------------------------------------------
//
// The PreProcess searches for the following input containers:
//  - MGeomCam
//  - MCalibrationCam
//  - MExtractedSignalCam
//
// The following output containers are also searched and created if
// they were not found:
//
//  - MCerPhotEvt
//
Int_t MCalibrate::PreProcess(MParList *pList)
{
    fSignals = (MExtractedSignalCam*)pList->FindObject("MExtractedSignalCam");
    if (!fSignals)
    {
        *fLog << err << "MExtractedSignalCam not found ... aborting" << endl;
        return kFALSE;
    }

    fCalibrations = (MCalibrationCam*)pList->FindObject("MCalibrationCam");
    if (!fCalibrations)
    {
        *fLog << err << "MCalibrationCam not found ... aborting." << endl;
        return kFALSE;
    }

    fCerPhotEvt = (MCerPhotEvt*)pList->FindCreateObj("MCerPhotEvt");
    if (!fCerPhotEvt)
        return kFALSE;
    
    return kTRUE;
}

// --------------------------------------------------------------------------
//
//
Int_t MCalibrate::Process()
{
  /*
    if (fCalibrations->GetNumPixels() != (UInt_t)fSignals->GetSize())
    {
        // FIXME: MExtractedSignal must be of variable size -
        //        like MCerPhotEvt - because we must be able
        //        to reduce size by zero supression
        //        For the moment this check could be done in ReInit...
        *fLog << err << "MExtractedSignal and MCalibrationCam have different sizes... abort." << endl;
        return kFALSE;
    }
  */

  UInt_t numpix = fSignals->GetSize();

  for (UInt_t pixid=0; pixid< numpix; pixid++)
    {
      const MCalibrationPix &pix = (*fCalibrations)[pixid];
      
      if (!pix.IsFitValid())
        continue;

      MExtractedSignalPix &sig =  (*fSignals)[pixid];
      
      Float_t signal;
      Float_t signalErr = 0.;
      
      if (sig.IsLoGainUsed())
        {
          signal    = sig.GetExtractedSignalLoGain()*pix.GetConversionHiLo();
          signalErr = signal*pix.GetConversionHiLoError();
        }
      else
        {
          signal = sig.GetExtractedSignalHiGain();
        }
      
      //      Float_t calibrationConversionFactor = pix.GetMeanConversionFFactorMethod();
      const Float_t calibrationConversionFactor      = pix.GetMeanConversionBlindPixelMethod();
      const Float_t calibrationConversionFactorError = pix.GetErrorConversionBlindPixelMethod();
      
      const Float_t nphot = signal*calibrationConversionFactor;

      Float_t nphotErr    = signal*calibrationConversionFactorError
                           *signal*calibrationConversionFactorError;

      nphotErr += signalErr*calibrationConversionFactor
                 *signalErr*calibrationConversionFactor;
      
      nphotErr  = TMath::Sqrt(nphotErr);
      
      fCerPhotEvt->AddPixel(pixid, nphot, nphotErr);
      
      if (sig.GetNumLoGainSaturated() > 0)
        (*fCerPhotEvt)[pixid].SetPixelSaturated();
    }
  
  fCerPhotEvt->FixSize();
  fCerPhotEvt->SetReadyToSave();
  
  return kTRUE;
}
