//____________________________________________________________________________
/*
 Copyright (c) 2003-2009, GENIE Neutrino MC Generator Collaboration
 For the full text of the license visit http://copyright.genie-mc.org
 or see $GENIE/LICENSE

 Author: Costas Andreopoulos <costas.andreopoulos \at stfc.ac.uk>
         STFC, Rutherford Appleton Laboratory - July 13, 2005

 For the class documentation see the corresponding header file.

 Important revisions after version 2.0.0 :
 @ Jun 23, 2008 - CA
   fCpuTime wasn't initialized.

*/
//____________________________________________________________________________

#include <sstream>
#include <fstream>
#include <cstdlib>

#include <TSystem.h>
#include <TMath.h>

#include "EVGCore/EventRecord.h"
#include "EVGDrivers/GMCJMonitor.h"
#include "GHEP/GHepParticle.h"
#include "Messenger/Messenger.h"
#include "Utils/PrintUtils.h"

using std::ostringstream;
using std::endl;
using std::ios;
using std::ofstream;

using namespace genie;

//____________________________________________________________________________
GMCJMonitor::GMCJMonitor(Long_t runnu) :
fRunNu(runnu)
{
  this->Init();
}
//____________________________________________________________________________
GMCJMonitor::~GMCJMonitor()
{

}
//____________________________________________________________________________
void GMCJMonitor::Update(int iev, const EventRecord * event)
{
  if(iev%fRefreshRate) return; // continue only every fRefreshRate events 

  fWatch.Stop();
  fCpuTime += (fWatch.CpuTime());

  ofstream out(fStatusFile.c_str(), ios::out);

  ostringstream status;

  status << endl;
  status << "Current Event Number: " << iev << endl;

  status << "Approximate total processing time: " 
                             << fCpuTime << " s" << endl;
  status << "Approximate processing time/event: " 
                     << fCpuTime/(iev+1) << " s" << endl;

  if(!event) status << "NULL" << endl;
  else       status << *event << endl;

  out << status.str();
  out.close();

  fWatch.Start();
}
//____________________________________________________________________________
void GMCJMonitor::Init(void)
{
  // build the filename of the GENIE status file
  ostringstream filename;
  filename   << "genie-mcjob-" << fRunNu << ".status";
  fStatusFile = filename.str();

  // create a stopwatch
  TStopwatch fWatch;
  fWatch.Reset(); 
  fWatch.Start();
  fCpuTime = 0;

  // get rehreah rate of set default / protect from invalid refresh rates
  if( gSystem->Getenv("GMCJMONREFRESH") ) {
   fRefreshRate = atoi( gSystem->Getenv("GMCJMONREFRESH") );
  } else fRefreshRate = 100;

  fRefreshRate = TMath::Max(1,fRefreshRate);
}
//____________________________________________________________________________

