// =====================================================================
//  $Id: sw00g4view.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();


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


  TCanvas canvas( "simmodule", "Geant4 View", 640, 480 );
  TH1D g4hist( "g4hist", "Beam energy spectrum", 6, 0.0, 6.0 );
  g4hist.Draw();

  Tstring idset[ 2 ] = { "Event Data", "Geant4" };
  TDataRecord record;

  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 );

      TDataElement ccdid = segment[ 0 ];
      TDataElement edep = segment[ 1 ];

      Tdouble id = *( ccdid.GetDoubleData() );
      Tdouble e = *( edep.GetDoubleData() );

      g4hist.Fill( id, e );
      canvas.Modified();
      canvas.Update();

    } else {
      break;
    }

    gSystem -> ProcessEvents();

  }

  theApplication -> Run();

  return( 0 );
}
