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

#define MONITORS

//Constants for analyses
//Event information
const int mPrimVertZbins = 1;                 //Number of z bins for analysis
const double mPrimVertZ[2] = {-1., 1.};       //Redefine values of the vertex Z for each run [cm]
const double mPrimVertR = 2.;                 //Distance in the XY plane [cm]
const double mPrimVertVpdVz[2] = {-5., 5.};   //VpdZ - TPCZ difference
const double mPrimVertXShift = 0.;
const double mPrimVertYShift = 0.;
const Bool_t mUseZdcCorrection = false;

//Track information
const double mChargedKaonMass = 0.493677;
const double mChargedPionMass = 0.13957018;
const int mPosCharge = +1;
const int mNegCharge = -1;
const int mTrackType = 1; 
const int mPythiaKaonCode = 321;              //Pythia particle code
const int mPythiaPionCode = 211;              //Pythia particle code

const int mTrackNHits[2] = {15, 50};          //Number of track hits
const double mTrackNHitsFit[2] = {15, 50};     //Number of track hits used in fit
const double mTrackDCA[2] = {0., 2.};      //DCA of the track and PV [cm]
const double mTrackASplitVal = 0.52;
const double mTrackMom[2] = {0.15, 1.55};     //General momentum of the track [GeV/c]
const double mTrackTransvMom[2] = {0.15, 1.55};  //General transverse momentum of the track [GeV/c]
const double mTrackEta[2] = { -1., 1.};

const short mDetectorSelection = 3;   

const double mTrackTpcMom[2] = {0.15, 0.55};  //Track momentum for TPC idnetification [GeV/c]
const double mnSigmaElectron[2] = {-1e9, 1e9};
const double mnSigmaPion[2]     = {-2.,  2.};
const double mnSigmaKaon[2]     = {-1e9, 1e9};
const double mnSigmaProton[2]   = {-1e9, 1e9};

const double mTrackTofMom[2] = {0.15, 1.55};   //Track momentum for ToF identification [GeV/c]
const double mPionTofMsqr[2] = {-0.02, 0.062}; //Based on p+p data
const double mKaonTofMsqr[2] = {0.20, 0.32};    //Based on p+p data

const double mTrackTnTMom[2]   = {0.15, 1.55};
const double mTnTNSigmaPion[2] = {-2., 2.};

//Pair information
const double mFmrCut[2] = {-1.1, 0.1};        //Not more than 10% of merged rows
const double mSplitLevelCut[2] = {-0.5, 0.6}; //Splitting level from paper. StHbtPair::quality()
const double mPairKt[2] = {0.,1.5};           //Pair transverse momentum cut
const double mPairQinv[2] = {0., 1.5};        //Pair relative momentum
const double mAveSep[2] = {5., 500.};         //Average separation of tracks within TPC

//Histograms values
const int mPairKtBins = 10;
const double mPairKtVal[2] = {0.1, 1.1};
const int mQinvBins = 120;               // 10 MeV/c^2 bin width
const double mQinvVal[2] = {0., 1.2};    // Redefine for each analysis

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

//_________________
void simPionHBT_pp510_1D(const Char_t *inFileList = defaultInFile,
                         const Char_t *oFileName = defaultOutFile,
                         int mult = 0)
{

  std::cout << "************************************" << std::endl
      << "*     simPionHBT_pp510_1D         *" << std::endl
      << "*            Start                 *" << std::endl
      << "************************************" << std::endl << 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("StFlowMaker");         // should be placed before HBT
  gSystem->Load("StHbtMaker");
  gSystem->Load("StarClassLibrary");
  gSystem->Load("StarGeneratorUtil");
  gSystem->Load("StarGeneratorEvent");
  gSystem->Load("StHbtStarGenReader");
  gSystem->Load("StRefMultCorr");
  gSystem->Load("libgsl");
  gSystem->Load("libgslcblas");

  std::cout << "Libraries have been successfully loaded" << std::endl;

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

  //
  // Set StHbtReader
  //
  std::cout << Form("Try to read file: %s", inFileList) << std::endl;

  StHbtStarGenReader *hijingReader = new StHbtStarGenReader("", inFileList, "root", -1);
  Long64_t mNEvents = hijingReader->GetNEvents();

  std::cout << Form("Number of events in TTree: %d", mNEvents) << std::endl;

  //
  // Set StHbtMaker and StHbtManager
  //
  StHbtMaker *mHbtMaker = new StHbtMaker();
  mHbtMaker->SetDebug(0);
  StHbtManager *mHbtManager = mHbtMaker->HbtManager();
  mHbtManager->SetEventReader(hijingReader);

  //
  // Set basic event cut
  //
  gregsEventCut *mBasicEventCut = new gregsEventCut();
  mBasicEventCut->SetCollisionType(0);     // 0-pp, 1-AuAu
  mBasicEventCut->SetEventMult(0, 180);
  mBasicEventCut->SetVertZPos(mPrimVertZ[0], mPrimVertZ[1]);
  mBasicEventCut->SetVzVpdVzDiff(mPrimVertVpdVz[0],mPrimVertVpdVz[1]);
  mBasicEventCut->SetVertRPos(mPrimVertR);
  mBasicEventCut->SetEventCentralityBins(0, 5);  // for 5 centrality bins
  //
  // Set basic pion single-particle cut
  //
  gregsSimpleTrackCut *mBasicTrackCut = new gregsSimpleTrackCut();
  mBasicTrackCut->SetCharge(mPosCharge);
  mBasicTrackCut->SetMass(mChargedPionMass);
  mBasicTrackCut->SetType(mTrackType);
  mBasicTrackCut->SetNHits(mTrackNHits[0], mTrackNHits[1]);
  mBasicTrackCut->SetNHitsFit(mTrackNHitsFit[0], mTrackNHitsFit[1]);
  mBasicTrackCut->SetAntiSplit(mTrackASplitVal);
  mBasicTrackCut->SetEta(mTrackEta[0], mTrackEta[1]);
  mBasicTrackCut->SetDCA(mTrackDCA[0], mTrackDCA[1]);
  mBasicTrackCut->SetDCAGlobal(mTrackDCA[0], mTrackDCA[1]);
  mBasicTrackCut->SetP(mTrackMom[0], mTrackMom[1]);

  mBasicTrackCut->SetDetectorSelection(mDetectorSelection);

  mBasicTrackCut->SetTpcMomentum(mTrackTpcMom[0], mTrackTpcMom[1]);
  mBasicTrackCut->SetNSigmaElectron(mnSigmaElectron[0],mnSigmaElectron[1]);
  mBasicTrackCut->SetNSigmaPion(mnSigmaPion[0], mnSigmaPion[1]);
  mBasicTrackCut->SetNSigmaKaon(mnSigmaKaon[0], mnSigmaKaon[1]);
  mBasicTrackCut->SetNSigmaProton(mnSigmaProton[0], mnSigmaProton[1]);

  mBasicTrackCut->SetTofMassSqr(mPionTofMsqr[0],mPionTofMsqr[1]);
  mBasicTrackCut->SetTofMomentum(mTrackTofMom[0], mTrackTofMom[1]);

  mBasicTrackCut->SetTnTMomentum(mTrackTnTMom[0], mTrackTnTMom[1]);
  mBasicTrackCut->SetTnTNSigmaPion(mTnTNSigmaPion[0], mTnTNSigmaPion[1]);

  //
  // Set basic pion pair cut
  //
  gregsTrackPairCut *mBasicPairCut = new gregsTrackPairCut();
  /*
  mBasicPairCut->SetFracOfMergedRow(mFmrCut[0],mFmrCut[1]);
  mBasicPairCut->SetQuality(mSplitLevelCut[0],mSplitLevelCut[1]);
  mBasicPairCut->SetKt(mPairKt[0],mPairKt[1]);
  mBasicPairCut->SetQinv(mPairQinv[0],mPairQinv[1]);
  mBasicPairCut->SetAverageSeparation(mAveSep[0],mAveSep[1]);
  */
  mBasicPairCut->SetEta(-999., 999.);

  Int_t mLocalCharge, mMultBins, mMultLow, mMultHi, mEvents2Mix;
  float ktLow, ktHi;

  //
  // The multiplicity analysis array, where
  // the first element corresponds to the particle charge: (pos, neg),
  // StHbtAnalysis, cut, CF and monitor declarations
  //
  StHbtVertexMultAnalysis *mPionMultAnalysis[2];

  //
  // Cuts
  //
  gregsEventCut       *mPionMultEventCut[2];
  gregsSimpleTrackCut *mPionMultTrackCut[2];
  gregsTrackPairCut   *mPionMultPairCut[2];

  //
  // Correlation functions
  //
  QinvCorrFctn *mPionQinvCF[2];

#ifdef MONITORS
  fxtEventCutMonitor *mFxtPionEventCutMonitorPass[2];
  fxtTrackCutMonitor *mFxtPionTrackCutMonitorPass[2];
  fxtPairCutMonitor  *mFxtPionPairCutMonitorPass[2];
  fxtEventCutMonitor *mFxtPionEventCutMonitorFail[2];
  fxtTrackCutMonitor *mFxtPionTrackCutMonitorFail[2];
  fxtPairCutMonitor  *mFxtPionPairCutMonitorFail[2];
#endif    

  std::cout << "---=== BEGIN CREATE ANALYSIS ===---\n";

  for (int iCharge = 0; iCharge < 1; iCharge++)
  {
    int charge = iCharge == 0 ? +1 : -1;
    //
    // Set multiplicity bins
    //
    switch(mult)
    {
      case 1:  mMultLow = 0;  mMultHi = 14;    mMultBins = 2; mEvents2Mix = 5; break;
      case 2:  mMultLow = 15; mMultHi = 22;    mMultBins = 2; mEvents2Mix = 5; break;
      case 3:  mMultLow = 23; mMultHi = 33;    mMultBins = 2; mEvents2Mix = 3; break;
      case 4:  mMultLow = 34; mMultHi = 48;    mMultBins = 2; mEvents2Mix = 3; break;
      case 5:  mMultLow = 49; mMultHi = 180;   mMultBins = 2; mEvents2Mix = 3; break;
      default: mMultLow = 0;  mMultHi = 180;   mMultBins = 5; mEvents2Mix = 4; break;
    }

    //
    // Create analysis
    //
    mPionMultAnalysis[iCharge] = new StHbtVertexMultAnalysis(mPrimVertZbins,
                                                             mPrimVertZ[0],
                                                             mPrimVertZ[1],
                                                             mMultBins,
                                                             mMultLow,
                                                             mMultHi);

    //
    // Create event cut
    //
    mPionMultEventCut[iCharge] = new gregsEventCut(*mBasicEventCut);
    mPionMultEventCut[iCharge]->SetEventMult(mMultLow, mMultHi);

    mPionMultAnalysis[iCharge]->SetEventCut(mPionMultEventCut[iCharge]);

#ifdef MONITORS
    mFxtPionEventCutMonitorPass[iCharge] = 
        new fxtEventCutMonitor("eventPionPass", Form("_%d_%d", iCharge, mult));
    mFxtPionEventCutMonitorFail[iCharge] = 
        new fxtEventCutMonitor("eventPionFail", Form("_%d_%d", iCharge, mult));
    mPionMultEventCut[iCharge]->AddCutMonitor(mFxtPionEventCutMonitorPass[iCharge],
                                              mFxtPionEventCutMonitorFail[iCharge]);
#endif

    //
    // Create single-track cuts and add them to the analysis
    //
    mPionMultTrackCut[iCharge] = new gregsSimpleTrackCut(*mBasicTrackCut);
    mPionMultTrackCut[iCharge]->SetCharge(charge);

    mPionMultAnalysis[iCharge]->SetFirstParticleCut(mPionMultTrackCut[iCharge]);
    mPionMultAnalysis[iCharge]->SetSecondParticleCut(mPionMultTrackCut[iCharge]);

#ifdef MONITORS
    mFxtPionTrackCutMonitorPass[iCharge] = 
        new fxtTrackCutMonitor(Form("_trackPionPass_%d_%d_", iCharge, mult), mChargedPionMass);
    mFxtPionTrackCutMonitorFail[iCharge] = 
        new fxtTrackCutMonitor(Form("_trackPionFail_%d_%d_", iCharge, mult), mChargedPionMass);
    mPionMultTrackCut[iCharge]->AddCutMonitor(mFxtPionTrackCutMonitorPass[iCharge],
                                              mFxtPionTrackCutMonitorFail[iCharge]);
#endif

    //
    // Create pair cut
    //
    mPionMultPairCut[iCharge] = new gregsTrackPairCut(*mBasicPairCut);

    mPionMultAnalysis[iCharge]->SetPairCut(mPionMultPairCut[iCharge]);

#ifdef MONITORS
    mFxtPionPairCutMonitorPass[iCharge] = 
        new fxtPairCutMonitor(Form("_pairPionPass_%d_%d_", iCharge, mult));
    mFxtPionPairCutMonitorPass[iCharge]->SetParticleMass(mChargedPionMass);
    mFxtPionPairCutMonitorFail[iCharge] = 
        new fxtPairCutMonitor(Form("_pairPionFail_%d_%d_", iCharge, mult));
    mFxtPionPairCutMonitorFail[iCharge]->SetParticleMass(mChargedPionMass);

    mPionMultPairCut[iCharge]->AddCutMonitor(mFxtPionPairCutMonitorPass[iCharge],
                                             mFxtPionPairCutMonitorFail[iCharge]);
#endif

    //
    // Correlation function initialization
    //
    // 1D
    mPionQinvCF[iCharge] = 
        new QinvCorrFctn(Form("hPionQinvMix_%d_%d", iCharge, mult),
                         mQinvBins, mQinvVal[0], mQinvVal[1]);
    //
    // Add correlation functions to the HbtManager
    //
    mPionMultAnalysis[iCharge]->AddCorrFctn(mPionQinvCF[iCharge]); 
    mPionMultAnalysis[iCharge]->SetNumEventsToMix(mEvents2Mix);   // set number of events to mix
    mHbtManager->AddAnalysis(mPionMultAnalysis[iCharge]);         // add analysis to the manager
  }

  std::cout << "---=== END CREATE ANALYSIS ===---\n";

  mChain->Init(); // StChain initialization

  //
  // Main loop over all events
  //
  Int_t   iRet = 0;
  Int_t   mNEventsProcessed = 0;
  Float_t mPercentCounter = 0.05;
  Float_t mProgress = 0.;

  unsigned int mSubCounter = 1;              // time
  time_t mStartTime, mStopTime, mDiffTime;   // time
  float mFrac;                               // time
  mStartTime = time(0);                      // time

  for(Int_t iEvent = 0; iEvent < mNEvents; iEvent++)
  {
    mProgress = (Float_t)iEvent / (Float_t)mNEvents;
    mNEventsProcessed++;

    if(mProgress >= mPercentCounter)
    {
      mPercentCounter += 0.05;
      mStopTime = time(0);
      mDiffTime = difftime(mStopTime, mStartTime);
      mFrac = (float)mDiffTime*(float)(mNEvents - iEvent)/(float)iEvent;
      mSubCounter++;
      std::cout << Form("Processing progress: %4.2f%%. Time left: %.1f sec", mProgress*100., mFrac)
          << std::endl;
    }

    mChain->Clear();
    iRet = mChain->Make(iEvent);
    if(iRet!=0)
    {
      std::cout << "expPionHBT_pau200_y2015_3D[ERROR] - iRet: " << iRet << std::endl;
      break;
    }
  }

  mChain->Finish();

  TFile *oFile = new TFile(oFileName, "RECREATE");          // create output file
  std::cout << "Writing histograms to the output file...";

  //
  // Write correlation function to the
  //   output file
  //
  for (int iCharge = 0; iCharge < 1; iCharge++)
  {
    mPionQinvCF[iCharge]->Numerator()->Write();
    mPionQinvCF[iCharge]->Denominator()->Write();
  }

#ifdef MONITORS
  for (int iCharge = 0; iCharge < 1; iCharge++)
  {
    mFxtPionEventCutMonitorPass[iCharge]->VertexZ()->Write();
    mFxtPionEventCutMonitorPass[iCharge]->VertexYvsVertexX()->Write();
    mFxtPionEventCutMonitorPass[iCharge]->RefMult()->Write();
    mFxtPionEventCutMonitorPass[iCharge]->VpdVzDiff()->Write();
    mFxtPionEventCutMonitorFail[iCharge]->VertexZ()->Write();
    mFxtPionEventCutMonitorFail[iCharge]->VertexYvsVertexX()->Write();
    mFxtPionEventCutMonitorFail[iCharge]->RefMult()->Write();
    mFxtPionEventCutMonitorFail[iCharge]->VpdVzDiff()->Write();

    mFxtPionTrackCutMonitorPass[iCharge]->DCAGlobal()->Write();
    mFxtPionTrackCutMonitorPass[iCharge]->Nhits()->Write();
    mFxtPionTrackCutMonitorPass[iCharge]->P()->Write();
    mFxtPionTrackCutMonitorPass[iCharge]->Pt()->Write();
    mFxtPionTrackCutMonitorPass[iCharge]->PtVsNsigmaPion()->Write();
    mFxtPionTrackCutMonitorPass[iCharge]->PtVsNsigmaKaon()->Write();
    mFxtPionTrackCutMonitorPass[iCharge]->PtVsNsigmaProton()->Write();
    mFxtPionTrackCutMonitorPass[iCharge]->PvsDedx()->Write();
    mFxtPionTrackCutMonitorPass[iCharge]->Rapidity()->Write();
    mFxtPionTrackCutMonitorPass[iCharge]->PseudoRapidity()->Write();
    mFxtPionTrackCutMonitorPass[iCharge]->PtVsMassSqr()->Write();
    mFxtPionTrackCutMonitorFail[iCharge]->DCAGlobal()->Write();
    mFxtPionTrackCutMonitorFail[iCharge]->Nhits()->Write();
    mFxtPionTrackCutMonitorFail[iCharge]->P()->Write();
    mFxtPionTrackCutMonitorFail[iCharge]->Pt()->Write();
    mFxtPionTrackCutMonitorFail[iCharge]->PtVsNsigmaPion()->Write();
    mFxtPionTrackCutMonitorFail[iCharge]->PtVsNsigmaKaon()->Write();
    mFxtPionTrackCutMonitorFail[iCharge]->PtVsNsigmaProton()->Write();
    mFxtPionTrackCutMonitorFail[iCharge]->PvsDedx()->Write();
    mFxtPionTrackCutMonitorFail[iCharge]->Rapidity()->Write();
    mFxtPionTrackCutMonitorFail[iCharge]->PseudoRapidity()->Write();
    mFxtPionTrackCutMonitorFail[iCharge]->PtVsMassSqr()->Write();

    mFxtPionPairCutMonitorPass[iCharge]->Kt()->Write();
    mFxtPionPairCutMonitorPass[iCharge]->Pt1Pt2Qinv()->Write();
    mFxtPionPairCutMonitorPass[iCharge]->FMRvsQinv()->Write();
    mFxtPionPairCutMonitorPass[iCharge]->SLvsQinv()->Write();
    mFxtPionPairCutMonitorPass[iCharge]->AveSepVsQinv()->Write();
    mFxtPionPairCutMonitorFail[iCharge]->Kt()->Write();
    mFxtPionPairCutMonitorFail[iCharge]->Pt1Pt2Qinv()->Write();
    mFxtPionPairCutMonitorFail[iCharge]->FMRvsQinv()->Write();
    mFxtPionPairCutMonitorFail[iCharge]->SLvsQinv()->Write();
    mFxtPionPairCutMonitorFail[iCharge]->AveSepVsQinv()->Write();
  } 
#endif

  std::cout << "\t[DONE]" << std::endl;

  //
  // Write the output file and close it
  //
  std::cout << "Saving the output file...";
  oFile->Write();
  oFile->Close();
  std::cout << "\t[DONE]" << std::endl;

  //
  // Delete chain and prompt
  //   last message :D
  //
  delete mChain;

  std::cout << "********************************" << std::endl
      << "*      simPionHBT_pp510_1D    *" << std::endl
      << "*              Finish          *" << std::endl
      << "********************************" << std::endl << std::endl;
}
