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

int main( int argc, char** argv, char** envv )
{
  if ( argc != 2 ) {
    Tcerr << "usage: " << argv[ 0 ] << Tspace << "<filename>" << Tendl;
    return( -1 );
  }

  TApplication* theApplication = rootinit();
  TFile f( "adc.root", "recreate" );

  Tstring filename = argv[ 1 ];
  TInputObjectFile ifile( filename );
  TDataRecord record;

  TCanvas canvas( "adc", "ADC VIEWER", 800, 800 );
  canvas.Divide( 4, 4, 0.0, 0.0 );

  TH1D adchist[ 16 ];
  for ( Tint i = 0; i < 16; i ++ ) {
    Tstring name = "adc" + itostr( i, 2 );
    Tstring title = "ADC #" + itostr( i, 2 );
    adchist[ i ] = TH1D( name.c_str(), title.c_str(), 50, 0, 4095 );
    adchist[ i ].SetStats( 0 );
    canvas.cd( i + 1 );
    adchist[ i ].Draw();
  }

  Tstring idset[ 2 ] = { "Event Data", "ADC" };

  while ( 1 ) {

    Tint datasize = ifile >> record;
    if ( datasize == 0 ) {
      ifile.SetOffset( ifile.GetTotalDataSize(), SEEK_SET );
      sleep( 1 );
      continue;
    }

    Tstring recid = record.GetID();

    if ( recid == "RUN BEGIN" ) {
      continue;
    } else if ( recid == "RUN END" ) {
      break;
    } else if ( recid == "EVENT" ) {

      TDataSegment segment;
      record.FindDataSegment( idset, segment );

      for ( Tint i = 0; i < 16; i ++ ) {
	TDataElement element = segment[ i ];
	Tint count = *( element.GetIntData() );
	adchist[ i ].Fill( (Tdouble)count );
        canvas.GetPad( i + 1 ) -> Modified();
        canvas.GetPad( i + 1 ) -> Update();
      }

      canvas.Modified();
      canvas.Update();

    } else {
      break;
    }

    gSystem -> ProcessEvents();

  }

  for ( Tint i = 0; i < 16; i ++ ) {
    adchist[ i ].Write();
  }
  f.Close();
  theApplication -> Run();

  return( 0 );
}
