// =====================================================================
//  $Id: St00OfflineDarkAverageMap.cc,v 1.1.1.1 2003/06/27 02:56:41 goiwai Exp $
//  $Name: CLDAQ-1-06-02 $
// =====================================================================
#include "St00OfflineDarkAverageMap.hh"
#include "TDataRecord.hh"
#include "TDataSection.hh"
#include "TDataSegment.hh"
#include "TDataElement.hh"
#include "TInputObjectFile.hh"

St00OfflineDarkAverageMap::St00OfflineDarkAverageMap( const Tstring& filename )
  : St00Map( filename ),
    theCounterMap( theNumberOfVerticalPixels, theNumberOfHorizontalPixels, 0 ),
    theNumberOfFrames( 0 )
{
  Tstring fadcidset[ 3 ] = { "EVENT", "ADC", "0" };
  TInputObjectFile ifile( theInputFileName );
  TDataRecord r;

  while ( ( ifile >> r ) != 0 ) {
    TDataElement e;
    if ( r.FindDataElement( fadcidset, e ) ) {
      Tshort* data = e.GetShortData();
      Tint ndata = e.GetNumberOfPrimitives();
      FillMap( data, ndata );
      theNumberOfFrames ++;
    } else {
      continue;
    }
  }

  for ( Tint row = 0; row < theMap.num_row(); row ++ ) {
    for ( Tint col = 0; col < theMap.num_col(); col ++ ) {
      theMap[ row ][ col ] = theMap[ row ][ col ] / theCounterMap[ row ][ col ];
    }
  }
}

St00OfflineDarkAverageMap::~St00OfflineDarkAverageMap()
{;}

Tvoid St00OfflineDarkAverageMap::FillMap( Tshort* data, Tint ndata )
{
  for ( Tint i = 0; i < ndata; i ++ ) {
    Tpixel_t pt = IsThisPixel( i );
    if ( pt == tIgnore ) {
      continue;
    } else if ( pt == tEffective ) {
      if ( data[ i ] >= 0 && data[ i ] <= 4095 ) {
	Tint colid = i % theRateOfVerticalShift;
	Tint rowid = i / theRateOfVerticalShift;
	theMap[ rowid ][ colid ] += (Tdouble)data[ i ];
	theCounterMap[ rowid ][ colid ] += 1.0;
      }
    } else if ( pt == tHoc ) {
      theHOCbuffer += data[ i ];
    } else if ( pt == tEndOfHoc ) {
      theHOCbuffer += data[ i ];
      Tdouble ave = theHOCbuffer / theNumberOfHorizontalOverClockPixels;
      Tint rowid = i / theRateOfVerticalShift;
      for ( Tint col = 0; col < theNumberOfHorizontalPixels; col ++ ) {
	theMap[ rowid ][ col ] -= ave;
      }
      theHOCbuffer = 0.0;
    }
  }
  return;
}
