#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 EventDisp(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("StChain");
  std::cout << "Libraries have been successfully loaded" << std::endl;

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

  StIOMaker *ioMaker = new StIOMaker("StIO", "r", inFileList);

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

  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);

    StuDraw3DEvent *event3d = new StuDraw3DEvent("TPC");
    StEvent *event = (StEvent *) chain->GetDataSet("StEvent");
    if (event) {
        StSPtrVecTrackNode& trackNode = event->trackNodes();
        UInt_t nTracks = trackNode.size();
        StGlobalTrack* gTrack = 0;
        StTrackNode *node = 0;
        for (UInt_t i=0; i < nTracks; i++) {
            node = trackNode[i]; if (!node) continue;
            gTrack = static_cast<StGlobalTrack*>(node->track(global));
            if (! gTrack) continue;
            if (gTrack->flag() < 0) continue;
            event3d->Track(*gTrack);
        }
        std::cout << "trying to diplay an event\n";
        event3d->Wait();
        event3d->Display();
    }
    else
        std::cout << "can't get StEvent\n";
    std::cout << "Press any key...";
    char key;
    std::cin >> key;

    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;
}
