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

const Char_t *defaultInFile  = "pp200_run12.list";
const Char_t *defaultOutFile = "PicoDstQA.root";

class StPicoDstQA;
class StPicoDstMaker;


void pp200_run12_QA(const char *inFileList  = defaultInFile,
                    const char *outFileName = defaultOutFile)
{
  std::cout << "**************************************" << std::endl
            << "*                                    *" << std::endl
            << "*  Hello, this is quality assurance  *" << std::endl
            << "*   for the pp200 PicoDst            *" << 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("StChain");
  gSystem->Load("StarClassLibrary");
  gSystem->Load("StFlowMaker");
  gSystem->Load("StHbtMaker");
  gSystem->Load("StPicoDstMaker");
  std::cout << "Libraries have been successfully loaded" << std::endl;

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

  //
  // Create PicoDst reader
  //
  std::cout << Form("Try to read file: %s", inFileList) << std::endl;
  StPicoDstMaker *picoMaker = new StPicoDstMaker(0, inFileList);
  StPicoDstQA    *QAmaker = new StPicoDstQA(picoMaker, outFileName);
  unsigned int trigWord = 0;
  for (int i = 0; i < 2; trigWord |= 1 << i++); // set only VPDMB
  std::cout << "TRIGGER WORD: " << trigWord << std::endl;
  QAmaker->SetTriggers(trigWord);
  QAmaker->SetRunIdParameters(80000, 13000000, 13080000);

  chain->Init();
  TChain         *currentTree = picoMaker->chain();
  Long64_t        nEvents = currentTree->GetEntries();
  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 (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;
}
