#include "MTdcSpect.h"

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

#include <TFile.h>

#include "MRawEvt.h"
#include "MParList.h"
#include "MHistosTdc.h"


////////////////////////////////////////////////////////////////////////
//
//  MTdcSpect.h
//
//  A Task to fill the raw Tdc values in the histograms to create 
//  the Tdc raw spectra
//

ClassImp(MTdcSpect)

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

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


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

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

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

Bool_t MTdcSpect::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->FillTdcHist ( fRawEvt->GetPixelId(i),
			    fRawEvt->GetPixelData(i) );
      
    }
  
  return kTRUE ;
}


Bool_t MTdcSpect::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 MHistosTdc 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;
}
