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



class StPicoDstMaker;


const char *inFile = "/star/data01/pwg/pusheax/data/MuDst/pp500/st_physics_12051052_raw_2010002.MuDst.root";

void Mu2Pico()
{
  //
  // Load libraries
  //
  std::cout << "Loading libraries..." << std::endl;
  gROOT->LoadMacro("$STAR/StRoot/StMuDSTMaker/COMMON/macros/loadSharedLibraries.C");
  loadSharedLibraries();
  gSystem->Load("libTable");
  gSystem->Load("libPhysics");
  gSystem->Load("St_base");
  gSystem->Load("StChain");
  gSystem->Load("St_Tables");
  gSystem->Load("StUtilities");        // new addition 22jul99
  gSystem->Load("StTreeMaker");
  gSystem->Load("StIOMaker");
  gSystem->Load("StarClassLibrary");
  gSystem->Load("StTriggerDataMaker"); // new starting from April 2003
  gSystem->Load("StBichsel");
  gSystem->Load("StEvent");
  gSystem->Load("StEventUtilities");
  gSystem->Load("StDbLib");
  gSystem->Load("StEmcUtil");
  gSystem->Load("StTofUtil");
  gSystem->Load("StPmdUtil");
  gSystem->Load("StPreEclMaker");
  gSystem->Load("StStrangeMuDstMaker");
  gSystem->Load("StMuDSTMaker");
  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 MuDstMaker
  //
  StMuDstMaker *MuDstMaker = new StMuDstMaker(0, 0, "", inFile, "MuDst", 100);
  MuDstMaker->SetStatus("*", 0);
  MuDstMaker->SetStatus("MuEvent", 1);
  MuDstMaker->SetStatus("PrimaryVertices", 1);
  MuDstMaker->SetStatus("PrimaryTracks", 1);
  MuDstMaker->SetStatus("GlobalTracks", 1);
  MuDstMaker->SetStatus("BTof*", 1);
  MuDstMaker->SetStatus("Emc*", 1);
  //
  // Create PicoDst reader
  //
  StPicoDstMaker *picoMaker = new StPicoDstMaker(1, inFile);
  picoMaker->setProdMode(0); // 0-mb, 1-central, 2-ht
  //
  // Init chain and do loop over events
  //
  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;
}
