// =====================================================================
//  $Id: St02OfflineDarkRmsMap.cc,v 1.3 2003/10/06 16:28:19 goiwai Exp $
//  $Name: CLDAQ-1-14-06 $
//  $Log: St02OfflineDarkRmsMap.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 "St02OfflineDarkRmsMap.hh"
#include "St02OfflineDarkAverageMap.hh"
#include "TDataRecord.hh"
#include "TDataSection.hh"
#include "TDataSegment.hh"
#include "TDataElement.hh"
#include "TDataMultiplicity.hh"
#include "TInputObjectFile.hh"

St02OfflineDarkRmsMap::St02OfflineDarkRmsMap( const Tstring& filename )
  : St02Map( filename ), theOfflineDarkAverageMap( theInputFileName )
{
  const TDataMultiplicity& avemap = theOfflineDarkAverageMap.GetMap();

  Tstring fadcidset[ 3 ] = { "EVENT", "ADC", "0" };
  TInputObjectFile ifile( theInputFileName );
  TDataRecord r;
  Tint nframe = 0;

  TDataMultiplicity mapbuf( theNumberOfVerticalPixels, theNumberOfHorizontalPixels, 0 );
  TDataMultiplicity diff( theNumberOfVerticalPixels, theNumberOfHorizontalPixels, 0 );


  //Xn=(x1+x2+x3+ ... + xn)/n
  //汛1=x1-Xn, 汛2=x2-Xn, 汛3=x3-Xn, ..., 汛n=xn-Xn
  //坌辣及爛聒
  //(考n)^2=(汛1)^2 + (汛2)^2 + (汛3)^2 + ... + (汛n)^2 / n
  //RMS午仄化 考n(n蜊及竅爛襖卞覆允月) 毛菲戶方丹午仄化引允

  while ( ( ifile >> r ) != 0 ) {
    TDataElement e;
    if ( r.FindDataElement( fadcidset, e ) ) {
      Tshort* data = e.GetShortData();
      Tint ndata = e.GetNumberOfPrimitives();
      FillMap( data, ndata );
      diff = theMap - avemap;
      for ( Tint row = 0; row < diff.num_row(); row ++ ) {
	for ( Tint col = 0; col < diff.num_col(); col ++ ) {
	  diff[ row ][ col ] *= diff[ row ][ col ];
	}
      }
      mapbuf += diff;
      nframe ++;
    } else {
      continue;
    }
  }

  theMap = mapbuf / nframe;

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

}

St02OfflineDarkRmsMap::~St02OfflineDarkRmsMap()
{;}
