#include "TROOT.h"
#include "TSystem.h"
#include "TChain.h"
#include "TFile.h"
#include "TString.h"
#include <iostream>

const Char_t *defaultInFile = "sample.list";
const Char_t *defaultOutFile = "oHijingQA.root";


void HijingQA(const Char_t *inFileList = defaultInFile,
	      const Char_t *outFileName = defaultOutFile)
{
  std::cout << "**************************************" << std::endl
            << "*                                    *" << std::endl
	    << "*  Hello, this is quality assurance  *" << std::endl
	    << "*   for the Hijing generator         *" << std::endl
	    << "*                                    *" << std::endl
            << "**************************************" << std::endl;
  
  //
  // Load libraries
  //
  std::cout << "Loading libraries..." << std::endl;
  gROOT->LoadMacro("$STAR/StRoot/StMuDSTMaker/COMMON/macros/loadSharedLibraries.C");
  loadSharedLibraries();
  gSystem->Load("libMinuit");
  gSystem->Load("libVMC");
  gSystem->Load("StChain");
  gSystem->Load("StarClassLibrary");
  gSystem->Load("StarGeneratorUtil");
  gSystem->Load("StarGeneratorEvent");
  gSystem->Load("StHijingQA");
  std::cout << "Libraries have been successfully loaded" << std::endl;

  //
  // Create chain
  //
  StChain *chain = new StChain("StChain");
  chain->SetDebug(0);

  //
  // Create MuDst reader
  //
  int nMaxFileToRead = 1e9;


  //
  // Create StMuDstQAMaker
  //
  StHijingQA *QAmaker = new StHijingQA("", inFileList, ".", 1e9, outFileName);
  chain->Init();
  unsigned int nEvents = QAmaker->GetNEvents();
  std::cout << Form("Number of events in TTree: %d", nEvents) << std::endl;
  Int_t iReturn = 0;
  Int_t nEventsProcessed = 0;
  Float_t percentCounter = 0.01;
  Float_t progress = 0.;

  for (unsigned int iEvent = 0; iEvent < nEvents; iEvent++)
  {
    progress = (Float_t)iEvent/(Float_t)nEvents;
    nEventsProcessed++;
    
    if(progress >= percentCounter)
    {
      percentCounter += 0.01;
      std::cout << Form("Processing progress: %4.2f%%", percentCounter*100.)
                << std::endl;
    }

    chain->Clear();
    iReturn = chain->Make(iEvent);
    if (iReturn != 0)
    {
      std::cout << "Error has been occured. Event processing has been stopped"
                << std::endl;
      break;
    }
  }

  chain->Finish();

  delete chain;
  
  std::cout << "*************************" << std::endl
	    << "*        Finish         *" << std::endl
	    << "*************************" << std::endl;
}
