// =====================================================================
//  $Id: OFFped.cc,v 1.1 2003/07/16 22:20:28 goiwai Exp $
//  $Name: CLDAQ-1-06-02 $
// =====================================================================
#include "TDataRecord.hh"
#include "TDataSection.hh"
#include "TDataSegment.hh"
#include "TDataElement.hh"
#include "TEnvironmentVariableTable.hh"
#include "TInputObjectFile.hh"

static const Tstring rcpath = "rs01setup";
static const Tint npin = 32;


static TInputObjectFile* ifile = 0;
static TEnvironmentVariableTable* envtable = 0;
static Tstring fpath;
static TDataRecord record;
static TDataElement element;
static Tdouble vdc[ npin ];
static Tdouble ped[ npin ];
static Tint pedevent;

static Tvoid initialize( Tint argc, Tchar** argv );
static Tvoid event();
static Tvoid runbegin();
static Tvoid runend();
static Tvoid sizezero();

int main( int argc, char** argv, char** envv )
{
  initialize( argc, argv );

  while ( 1 ) {
    Tint datasize = ifile -> Read( record );
    if ( datasize == 0 ) {
      sizezero();
      continue;
    }

    Tstring recid = record.GetID();
    if ( recid == "RUN BEGIN" ) {
      runbegin();
      continue;
    } else if ( recid == "EVENT" ) {
      event();
    } else if ( recid == "RUN END" ) {
      runend();
      break;
    } else {
      Tcerr << "unknown tag: " << recid << Tendl;
      break;
    }
  }

  return( 0 );
}

Tvoid initialize( Tint argc, Tchar** argv )
{
  if ( argc != 2 ) {
    Tcerr << "usage: " << argv[ 0 ] << " <run#>" << Tendl;
    exit( -1 );
  }

  Tint runid = (Tint)strtol( argv[ 1 ], 0, 0 );
  Tstring runidstr = itostr( runid );

  envtable = new TEnvironmentVariableTable ( rcpath );
  Tstring rechead = envtable -> GetEnvironmentValue( "RS01_RECORD_HEAD" );
  Tstring recpath = envtable -> GetEnvironmentValue( "RS01_RECORD_DIR" );
  fpath = recpath + Tslash + rechead + runidstr + ".drec";
  ifile = new TInputObjectFile( fpath );

  pedevent = envtable -> GetIntegerValue( "RS_01_PEDESTAL_EVENT" );

  for ( Tint ch = 0; ch < npin; ch ++ ) {
    ped[ ch ] = 0.0;
  }

  return;
}

Tvoid event()
{
  for ( Tint ch = 0; ch < npin; ch ++ ) {
    // VDCのスナップショット
    element = record[ 1 ][ ch ][ 0 ];
    element.StorePrimitives( &vdc[ ch ] );

    ped[ ch ] += vdc[ ch ];
  }


  element = record[ 0 ][ 0 ][ 0 ];
  Tint eventid;
  element.StorePrimitives( &eventid );
  if ( eventid == pedevent - 1 ) {
    Tstring head = "RS01_PEDESTAL_";
    for ( Tint ch = 0; ch < npin; ch ++ ) {
      Tdouble p = ped[ ch ] / (Tdouble)pedevent;
      Tcout << head << itostr( ch, 2 ) << " " << p << Tendl;
    }
    exit( 0 );
  }

  return;
}

Tvoid runbegin()
{
  return;
}

Tvoid runend()
{
  Tcout << "too short this run." << Tendl;
  Tcout << "reduce [RS_01_PEDESTAL_EVENT] value." << Tendl;
  return;
}

Tvoid sizezero()
{
  ifile -> SetOffset( ifile -> GetTotalDataSize(), SEEK_SET );
  usleep( 1000*1000 );
  return;
}
