// =====================================================================
//  $Id: st00pureeventview.cc,v 1.1.1.1 2003/06/27 02:56:41 goiwai Exp $
//  $Name: CLDAQ-1-06-02 $
// =====================================================================
#include <TROOT.h>
#include <TSystem.h>
#include <TApplication.h> 
#include <TStyle.h>
#include <TGraph.h>
#include <TH1.h>
#include <TH2.h>
#include <TCanvas.h>
#include <TNtuple.h>
#include <TFile.h>
#include <TPad.h>

#include "TDataRecord.hh"
#include "TDataSection.hh"
#include "TDataSegment.hh"
#include "TDataElement.hh"
#include "TInputObjectFile.hh"

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


  TApplication* theApplication = new TApplication( "root-analyser", 0, 0 );
  gROOT -> Reset( 0 );
  gStyle -> SetStatColor(42);
  gStyle -> SetTitleColor(42);
  gStyle -> SetFrameFillColor( 21 );
  gStyle -> SetFrameFillStyle( 1 );
  gStyle -> SetMarkerStyle( 7 );
  gStyle -> SetFuncColor( 4 );
  gStyle -> SetOptStat( 1111110 );
  gStyle -> SetOptFit( 1111 );
  gStyle -> SetPadGridX( kTRUE );
  gStyle -> SetPadGridY( kTRUE );

  TCanvas cv( "CVfadc", "Pentland MPX201A" );
  TH1D mpx201a( "mpx201a", htitle.c_str(), 400, 0.0, 4096.0 );
  mpx201a.SetFillColor( 45 );


  Tstring fadcidset[ 3 ] = { "EVENT", "ADC", "0" };
  TDataRecord record;

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

    TDataElement element;
    Tstring recid = record.GetID();

    if ( recid == "RUN BEGIN" ) {
      continue;
    } else if ( recid == "EVENT" ) {
      record.FindDataElement( fadcidset, element );
      Tshort* data = element.GetShortData();
      Tint ndata = element.GetNumberOfPrimitives();
      cv.cd();
      for ( Tint i = 0; i < ndata; i ++ ) {
	mpx201a.Fill( data[ i ] );
      }
      mpx201a.Draw();
      cv.Modified();
      cv.Update();
    } else if ( recid == "RUN END" ) {
      break;
    } else {
      Tcerr << "unknown tag: " << recid << Tendl;
    }
    gSystem -> ProcessEvents();
  }

  theApplication -> Run();

  return( 0 );
}
