/////////////////////////////////////////////////////////////////////////////
//                                                                         //
// MReadCT1Ascii                                                           //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////

#include "MReadCT1Ascii.h"


#include <stdio.h>
#include <iostream.h>
#include <fstream.h>

#include "MParList.h"
#include "MCerPhotEvt.h"

ClassImp(MReadCT1Ascii)

MReadCT1Ascii::MReadCT1Ascii(const char *fname,
			     const char *name, 
			     const char *title)
{
    *fName  = name  ? name  : "MReadCT1Ascii";
    *fTitle = title ? title : "Task to loop over events in CT1 ascii file";

    // open the input stream

    fFileName = fname;

    // set the pedestals to default values 
    
    for (Int_t i = 0; i<127; i++ )
      {
	
	fPedest[i] = 1.5  ; 
      } 
    
}

Bool_t MReadCT1Ascii::PreProcess(MParList *pList)
{
  // Preprocessing 

  //  open the file cout << fFileName << endl ; 
  
  fInputfile = fopen( fFileName, "r" ) ; 
 
  if ( fInputfile == 0 ) 
    return kFALSE ; 
  
  //  look for the MCerPhotEvt class in the plist

    
  fNphot = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
  
  if (!fNphot )
    {
      cout << "MRawCT1Ascii::PreProcess - WARNING: MCerPhotEvt not found... exit" << endl;
      return kFALSE ; 
    }

  return kTRUE;
}

Bool_t MReadCT1Ascii::Process()
{
  fNphot->Clear() ; 
  
  Int_t   dummyI ; 
  Float_t dummyF ; 

  //    read in the first five numbers 

  fscanf ( fInputfile, "%d", &dummyI ) ; 
  if ( feof ( fInputfile ) != 0 ) 
    return kFALSE ; 

  // if the first number is negativ this is the pedestal line
  
  if (dummyI < 0 )
    ReadPedestal() ; 

  fscanf ( fInputfile, "%d", &dummyI ) ; 
  fscanf ( fInputfile, "%d", &dummyI ) ; 
  fscanf ( fInputfile, "%d", &dummyI ) ; 
  fscanf ( fInputfile, "%d", &dummyI ) ; 

  //    read in the next 127 numbers as the pixels

  for (Int_t i = 0; i<127; i++ )
    {
      fscanf ( fInputfile, "%f", &dummyF ) ;
      
      if ( dummyF > 0.0 ) { 
	fNphot->AddPixel(i, dummyF, fPedest[i] ) ; 
      } 
      
    }

  return kTRUE;
}

Bool_t MReadCT1Ascii::PostProcess()
{
  fclose( fInputfile ) ;   
  return kTRUE;
}


void MReadCT1Ascii::ReadPedestal() 
{ 
  cout << " Read in the Pedestals " << endl ; 
  Int_t   dummyI ; 
  Float_t dummyF ; 
  
  // the next for values are for dummy 
  fscanf ( fInputfile, "%d", &dummyI ) ; 
  fscanf ( fInputfile, "%d", &dummyI ) ; 
  fscanf ( fInputfile, "%d", &dummyI ) ; 
  fscanf ( fInputfile, "%d", &dummyI ) ; 

  //    read in the next 127 numbers as the pedestals

  for (Int_t i = 0; i<127; i++ )
    {
      fscanf ( fInputfile, "%f", &dummyF ) ;
      
      if ( dummyF > 0.0 ) { 
	fPedest[i] = dummyF ; 
      } 
      
    }

  fscanf ( fInputfile, "%d", &dummyI ) ; 


} 

