//
//
//
//
//
//
#include <stdlib.h>
#include <stdio.h>

#include "COREventHeader.hxx"
#include "CORParticle.hxx"
#include "CORStatfile.hxx"

int main(int argc, char **argv)
{
  char  path[100] = "" ; 

  char  cername[120] ; 
  char  datname[120] ; 
  
  ifstream   cerfile ; 
  
  COREventHeader Event ;   
  CORParticle    Photon ; 
  
  Int_t iPhotonInShower ; 
  Int_t iShowers = 0 ; 
  
  Float_t lambda ; 

  cout << " ============================" << endl ; 
  cout << " SIMONE" << endl ; 
  cout << "                             " << endl ; 
  cout << " SImulated MONte carlo Events" << endl ; 
  cout << "                             " << endl ; 


  if ( argc <= 1 ) {
    cout << endl ; 
    cout << " INFO: You have to start the program with "<<endl <<endl ; 
    cout << "        -> simone DIRECTORY_WITH_CER_FILES" <<endl <<endl ; 
    cout << "        no SLASH at the end of the directory name"<<endl ; 
    cout << "        (example: -> simone /hd123/Protons   "<<endl ; 
    exit (-1) ; 
  }

  // copy the argument to filename 

  sprintf (cername , "%s", argv[1] ) ; 

    
  cout << cername  << endl ; 
      
  //
  //   try to open the files
  // 
    
  cerfile.open( cername );
    
  if ( cerfile.bad() ) { 
    cout << "Cannot open input file:  " << cername << endl ;
    exit (1) ; 
  }
    
  //   
  //    cout << " Read event " << endl ;
  //
  
  //   tricky stuff. We read in the RunHeader which has by chance the
  //   same sice than the EventHeader
  Event.read( cerfile ); 
  Event.Print() ; 
  //    now we read in the event 
  
  while( ! (cerfile.eof() || cerfile.bad() )) {
    
    Event.read( cerfile );
  
    Event.Print() ; 
    
    iShowers++ ; 

    //
    //   loop over the particles (cerenkov photons) in 
    //   the file 
    //
    
    iPhotonInShower = 0 ; 
    
    while( ! (cerfile.eof() || cerfile.bad() )) {

      //
      //   read in the particles
      //
      
      Photon.read ( cerfile ) ; 
      
      //
      //   only if the wavelength lambda is greater than 
      //   1.0 it is a real cerenkov photon 
      //
      lambda = Photon.get_wl() ; 
      
      //      Photon.print() ; 
      
      if ( lambda < 1.0 ) { 
	// here we got to the next event reading in all the ZERO 
	// from the file 
	while ( lambda < 1. && ! (cerfile.eof() || cerfile.bad() ) ) { 
	  
	  Photon.read ( cerfile ) ; 
	  lambda = Photon.get_wl() ;	
	  //	  cout << lambda << endl ; 
	} 
	
	//	go back in the file
	cerfile.seekg( -28, ios::cur  ) ; 
	
	//  read in an Event footer or something like that
	Event.read( cerfile );
	
	break ; 
      } 
      
      iPhotonInShower++ ; 
      
    }
    
    cout << "Number of Photons In Shower: " 
	 <<  iPhotonInShower << endl ; 
    
	

  }
  
  //
  //   close the file
  //
  
  cerfile.close();  
  
}


