/////////////////////////////////////////////////////////////////////////////
//                                                                         //
//   MCerPhotCalc                                                          //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////

#include "MCerPhotCalc.h"

#include "MParList.h"

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

#include "MRawEvtPixelIter.h"
#include "MCerPhotEvt.h"
#include "MPedestalPix.h"
#include "MPedestalCam.h"

ClassImp(MCerPhotCalc)

    MRawEvtData  *fRawEvt;     // raw event data (time slices)
    MPedestalCam *fPedestals;  // Pedestals of all pixels in the camera
    MCerPhotEvt  *fCerPhotEvt; // Cerenkov Photon Event used for calculation

MCerPhotCalc::MCerPhotCalc(const char *name, const char *title)
{
    *fName  = name  ? name  : "MCerPhotCalc";
    *fTitle = title ? title : "Task to calculate Cerenkov photons from raw data";
}

Bool_t MCerPhotCalc::PreProcess( MParList *pList )
{
    fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
    if (!fRawEvt)
    {
        *fLog << dbginf << "MRawEvtData not found... aborting." << endl;
        return kFALSE;
    }

    fPedestals = (MPedestalCam*)pList->FindObject("MPedestalCam");
    if (!fPedestals)
    {
        *fLog << dbginf << "MPedestalCam not found... aborting." << endl;
        return kFALSE;
    }

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

    return kTRUE;
}

Bool_t MCerPhotCalc::Process()
{
    fCerPhotEvt->Clear();

    MRawEvtPixelIter pixel(fRawEvt);

    while (pixel.Next())
    {
        const UInt_t pixid = pixel.GetPixelId();

        const MPedestalPix &ped = (*fPedestals)[pixid];

        const Float_t nphot = (Float_t)pixel.GetSumHiGainFadcSamples() - ped.GetMean();
        fCerPhotEvt->AddPixel(pixid, nphot, 0);

        // FIXME! Handling of Lo Gains is missing!
    }

    return kTRUE;
}

