// =====================================================================
//  $Id: St02OfflineDarkAverageMap.cc,v 1.3 2003/10/06 16:28:19 goiwai Exp $
//  $Name: CLDAQ-1-14-06 $
//  $Log: St02OfflineDarkAverageMap.cc,v $
//  Revision 1.3  2003/10/06 16:28:19  goiwai
//  *** empty log message ***
//
//  Revision 1.2  2003/07/30 16:16:34  goiwai
//  ファイルにコミットログをつけることにしました.
//
// =====================================================================
#include "St02OfflineDarkAverageMap.hh"
#include "TDataRecord.hh"
#include "TDataSection.hh"
#include "TDataSegment.hh"
#include "TDataElement.hh"
#include "TInputObjectFile.hh"

St02OfflineDarkAverageMap::St02OfflineDarkAverageMap( const Tstring& filename )
  : St02Map( 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 ];
    }
  }
}

St02OfflineDarkAverageMap::~St02OfflineDarkAverageMap()
{;}

Tvoid St02OfflineDarkAverageMap::FillMap( Tshort* data, Tint ndata )
{
  for ( Tint i = 0; i < ndata; i ++ ) {
    Tpixel_t pt = IsThisPixel( i );
    Tint colid = i % theRateOfVerticalShift - theHorizontalOffset;
    Tint rowid = i / theRateOfVerticalShift - theVerticalOffset;

    if ( pt == tSignal && data[ i ] >= 0 && data[ i ] <= 4095 ) {
      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 / (Tdouble)theNumberOfHorizontalOverClockPixels;
      for ( Tint col = 0; col < theNumberOfHorizontalPixels; col ++ ) {
	theMap[ rowid ][ col ] -= ave;
      }
      theHOCbuffer = 0.0;
    } else if ( rowid >= 256 ) {
      break;
    }
  }

  return;
}
