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

const Char_t *defaultInFile = "test.list";
const Char_t *defaultOutFile = "oMuDstQA.root";


void MuDstQA(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 MuDst                    *" << 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("StMuDSTMaker");
  gSystem->Load("StChain");
//  gSystem->Load("StarClassLibrary"); 
  gSystem->Load("StTpcPidQA");
  std::cout << "Libraries have been successfully loaded" << std::endl;

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

  //
  // Create MuDst reader
  //
  int nMaxFileToRead = 1e9;
  std::cout << Form("Try to read file: %s", inFileList) << std::endl;
  StMuDstMaker *muDstMaker = new StMuDstMaker(0, 0, "", inFileList, "MuDst", nMaxFileToRead);
  muDstMaker->SetStatus("*",0);
  muDstMaker->SetStatus("Event*",1);
  muDstMaker->SetStatus("MuEvent*",1);
  muDstMaker->SetStatus("PrimaryVertices*",1);
  muDstMaker->SetStatus("PrimaryTracks*",1);
  muDstMaker->SetStatus("GlobalTracks*",1);
  muDstMaker->SetStatus("BTofHeader*",1);
  TChain *currentTree = muDstMaker->chain();
  Long64_t nEvents = currentTree->GetEntries();
  std::cout << Form("Number of events in TTree: %d", nEvents) << std::endl;

  //
  // Create StTpcPidQA
  //
  StTpcPidQA *QAmaker = new StTpcPidQA;
  QAmaker->mMuDstMaker = muDstMaker;
  QAmaker->mFileName = outFileName;

  chain->Init();
  Int_t iReturn = 0;
  Int_t nEventsProcessed = 0;
  Float_t percentCounter = 0.01;
  Float_t progress = 0.;

  for (Int_t 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;
}
