////////////////////////////////////////////////////////////////////////
//
//  MFillHFadc
//
//  This task fill the n time slices from all pixels
//  (stored in a MRawEvtData container) into histograms.
//  This histograms (one per pixel) are stored in MHFadcCam, MHFadcPix
//
////////////////////////////////////////////////////////////////////////

#include "MFillHFadc.h"

#include "MLog.h"
#include "MLogManip.h"
#include "MParList.h"
#include "MHFadcCam.h"
#include "MRawEvtData.h"
#include "MRawEvtPixelIter.h"

ClassImp(MFillHFadc)

MFillHFadc::MFillHFadc (const char *name, const char *title) : fRawEvtData(NULL)
{
  *fName  = name  ? name  : "MFillHFadc";
  *fTitle = title ? title : "Task to fill the adc spectra with  raw data";
}

Bool_t MFillHFadc::PreProcess (MParList *pList)
{
    //
    // The PrProcess function checks for the existance of all necessary
    // parameter containers
    //

    //
    // check if all necessary input containers are existing
    //
    fRawEvtData = (MRawEvtData*)pList->FindCreateObj("MRawEvtData");
    if (!fRawEvtData)
    {
        *fLog << dbginf << " Error: MRawEvtData not found... exit." << endl;
        return kFALSE;
    }

    //
    // check if the output containers are existing, if not craete them
    //
    fHistos = (MHFadcCam*)pList->FindCreateObj("MHFadcCam");
    if (!fHistos)
        return kFALSE;

    return kTRUE;
} 

Bool_t MFillHFadc::Process()
{
    //
    // This process function loops over all pixels in an MRawEvtData
    // event and fills the values into histograms
    //

    //  loop over the pixels and fill the values in the histograms
  
    MRawEvtPixelIter pixel(fRawEvtData);

    const Int_t nhisamples = fRawEvtData->GetNumHiGainSamples() ;
    const Int_t nlosamples = fRawEvtData->GetNumLoGainSamples() ;

    //  cout << "HighSamples " << iHighSamples ;

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

        for (Int_t i=0;  i<nhisamples; i++)
            fHistos->FillHi(id, pixel.GetHiGainFadcSamples()[i]);

        if (!pixel.HasLoGain())
            continue;

        for (Int_t i=0; i<nlosamples; i++)
            fHistos->FillLo(id, pixel.GetLoGainFadcSamples()[i]);
    }

    return kTRUE;

}
