#include "MAdcSpect.h"

#include <iostream.h>
#include <stdlib.h>

#include <TFile.h>

#include "MRawEvt.h"
#include "MParList.h"
#include "MHistosAdc.h"


////////////////////////////////////////////////////////////////////////
//
//  MAdcSpect.h
//
//  A Task to fill the raw ADC values in the histograms to create 
//  the ADC raw spectra
//

ClassImp(MAdcSpect)

MAdcSpect::MAdcSpect( char* treeName, char *rootfile)
{
  //
  //   default constructor
  //
  sprintf(fTreeName, "%s", treeName ) ; 

  sprintf(fOutFile, "%s", rootfile);
}


Bool_t MAdcSpect::PreProcess(MParList *pList)
{
  //
  //   Do the preprocessing for MAdcSpect
  // 
  //   Connects the event in MRawEvtBuf as the input for this task
  //   and the MHistosAdc container as the output 
  //

  //
  //   first look for the input buffer MRawEvtBuf
  //  
  fEvtBuf = (MObjBuffer*) pList->FindObject(fTreeName);
  if (!fEvtBuf)
    {
      cout << "ERROR: MAdcSpect::PreProc(): " << fTreeName << " not found!" << endl;
      exit(1);
    }

  //
  //  second connect the output container 
  //
  fHists = (MHistosAdc*) pList->FindObject("MHistosAdc");
  
  if (!fHists)
    {
      cout << "ERROR: MAdcSpect::PreProc(): MHistosAdc not found!" << endl;
      exit(1);
    }
  
  return kTRUE ; 
}

Bool_t MAdcSpect::Process()
{
  //
  //  fill the raw data values in the corresponding histograms
  //
  
  //
  //   loop over the pixels in the events
  //
  
  MRawEvt *fRawEvt = (MRawEvt*)(*fEvtBuf)();
  
  for ( Int_t i=0 ;  i< (Int_t) fRawEvt->GetMultPixel(); i++ )
    {
      fHists->FillAdcHist ( fRawEvt->GetPixelId(i),
			    fRawEvt->GetPixelData(i) );
      
    }
  
  return kTRUE ;
}


Bool_t MAdcSpect::PostProcess()
{
    //
    //  PostProessing
    //
    //  after the loop over all events this routine is executed.
    //  Here the postprecessing is checking the contents of
    //  fOutFile.
    //  If it is "nooutput", nothing is done.
    //  Else the histograms in the MHistosAdc are written to a file.
    //

    if (strcmp (fOutFile, "nooutput"))
    {
        //
        //   write the histograms to File
        //
        cout << endl << "--> INFO: write the histograms to file: "
            << fOutFile  << endl ;

        //
        //   call the containers save function
        //

        fHists->SaveHist(fOutFile);
    }

    return kTRUE;
}
