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

//
// To define cut monitors
// uncomments line below
//
// #define MONITORS

//
// Constants for analyses
//

#define MULT_BINS 7
#define CHARGE_BINS 2

//
//  Event information
//
const int mPrimVertZbins = 6;                // number of z bins for analysis
const double mPrimVertZ[2] = {-30., 30.};    // 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 mUseZdcCorrection = true;         // valid for AuAu collisions. True for 200GeV only!

//
// Track information
//
const double mChargedKaonMass = 0.493677;
const double mChargedPionMass = 0.13957018;
const int mPosCharge = +1;
const int mNegCharge = -1;
const int mTrackType = 1;                     // primary track
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 = 4;  // 0-TPC, 1-ToF, 2-TPC+ToF, 3-ToF||TPC, 4-TPC&&TOF(P>Pthr)||TPC(P<Pthr)

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.18, 0.3};    // based on p+p data

const double mTrackTnTMom[2] = {0.15, 1.55};
const double mTnTNSigmaElectron[2] = {-1e9, 1e9};
const double mTnTNSigmaPion[2] = {-2., 2.};
const double mTnTNSigmaKaon[2] = {-1e9., 1e9.};
const double mTnTNSigmaProton[2] = {-1e9, 1e9};

const double mTTTMomThresh = 0.45; // TPC&&TOF (P>Pthr)||TPC(P<Pthr)

//
// 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., 5000.};         // average separation of tracks within TPC

//
// Histograms values
//
const int mPairKtBins = 22;                 // bin width 
const double mPairKtVal[2] = {0.05, 1.15};  // 50 MeV/c 
const int mQinvBins = 80;                      // 10 MeV/c^2 bin width
const double mQinvVal[2] = {0., 0.8};          // redefine for each analysis

const Char_t *defaultInFile = "pions.list";
const Char_t *defaultOutFile = "oExpPion_pp500_1D.root";



//_________________
void expPionHBT_pp500_FemtoDst_1D(const Char_t *inFileList = defaultInFile,
				  const Char_t *oFileName  = defaultOutFile) {


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

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

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

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

  //
  // Set StHbtReader
  //
  StHbtFemtoDstReader *femtoReader = new StHbtFemtoDstReader("", inFileList, "root", -1, false);
  femtoReader->AddTrigId(320000);  // trigger selection for pp500 y2011
  femtoReader->AddTrigId(320001);
  femtoReader->AddTrigId(320011);
  femtoReader->AddTrigId(320021);
  femtoReader->AddTrigId(330021);
  Long64_t mNEvents = femtoReader->GetNEvents();
  mHbtManager->SetEventReader(femtoReader);

  //
  // Set basic event cut
  //
  gregsEventCut *mBasicEventCut = new gregsEventCut();
  mBasicEventCut->SetCollisionType(0);     //0-pp, 1-AuAu
  mBasicEventCut->SetEventMult(0, 45);
  mBasicEventCut->SetVertZPos(mPrimVertZ[0], mPrimVertZ[1]);
  mBasicEventCut->SetVzVpdVzDiff(mPrimVertVpdVz[0],mPrimVertVpdVz[1]);
  mBasicEventCut->SetVertRPos(mPrimVertR);

  //
  // Set basic kaon 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->SetTnTNSigmaElectron(mTnTNSigmaElectron[0], mTnTNSigmaElectron[1]);
  mBasicTrackCut->SetTnTNSigmaPion(mTnTNSigmaPion[0], mTnTNSigmaPion[1]);
  mBasicTrackCut->SetTnTNSigmaKaon(mTnTNSigmaKaon[0], mTnTNSigmaKaon[1]);
  mBasicTrackCut->SetTnTNSigmaProton(mTnTNSigmaProton[0], mTnTNSigmaProton[1]);

  mBasicTrackCut->SetTTTMomentumThresh(mTTTMomThresh);

  //
  // Set basic kaon 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]);

  Int_t mLocalCharge, mMultBins, mMultLow, mMultHi, mEvents2Mix, mCurrentPid;

  //
  // The multiplicity analysis matrix is CHARGE_BINS x MULT_BINS, where
  // the first element corresponds to the particle charge: (pos, neg),
  // and the second one corresponds to the RefMult intervals as listed below:
  // Mult: 0-45, 0-2, 3-4, 5-6, 7-8, 9-10, 11-45
  //

  StHbtVertexMultAnalysis *mPionMultAnalysis[CHARGE_BINS][MULT_BINS]; // StHbtAnalysis, cut, CF and monitor declarations

  //
  // Cuts
  //
  gregsEventCut       *mPionEventCut[CHARGE_BINS][MULT_BINS];
  gregsSimpleTrackCut *mPionTrackCut[CHARGE_BINS][MULT_BINS];
  gregsTrackPairCut   *mPionPairCut[CHARGE_BINS][MULT_BINS];

  //
  // CorrFctns
  //
  QinvCorrFctnKt                *mPionQinvMixKtCF[CHARGE_BINS];
  QinvCorrFctnOpposHemisphereKt *mPionQinvOppKtCF[CHARGE_BINS];
  QinvCorrFctnRotationKt        *mPionQinvRotKtCF[CHARGE_BINS];
  QinvCorrFctn                  *mPionQinvMixMultCF[CHARGE_BINS][MULT_BINS];
  QinvCorrFctnOpposHemisphere   *mPionQinvOppMultCF[CHARGE_BINS][MULT_BINS];
  QinvCorrFctnRotation          *mPionQinvRotMultCF[CHARGE_BINS][MULT_BINS];

#ifdef MONITORS
  //
  // Cut monitors
  //
  fxtEventCutMonitor *mFxtPionEventCutMonitorPass[MULT_BINS];
  fxtTrackCutMonitor *mFxtPionTrackCutMonitorPass[CHARGE_BINS][MULT_BINS];
  fxtPairCutMonitor  *mFxtPionPairCutMonitorPass[CHARGE_BINS][MULT_BINS];
  fxtEventCutMonitor *mFxtPionEventCutMonitorFail[CHARGE_BINS][MULT_BINS];
  fxtTrackCutMonitor *mFxtPionTrackCutMonitorFail[CHARGE_BINS][MULT_BINS];
  fxtPairCutMonitor  *mFxtPionPairCutMonitorFail[CHARGE_BINS][MULT_BINS];
#endif

  //
  // Analysis creation
  //
  for(Int_t iMult = 0; iMult < MULT_BINS; iMult++) {
    for(Int_t iCharge = 0; iCharge < CHARGE_BINS; iCharge++) {
      switch(iMult) {
      case 1:  mMultLow = 0;  mMultHi = 2;  mMultBins = 1;  mEvents2Mix = 10; break;
      case 2:  mMultLow = 3;  mMultHi = 4;  mMultBins = 1;  mEvents2Mix = 10; break;
      case 3:  mMultLow = 5;  mMultHi = 6;  mMultBins = 1;  mEvents2Mix = 10; break;
      case 4:  mMultLow = 7;  mMultHi = 8;  mMultBins = 1;  mEvents2Mix = 10; break;
      case 5:  mMultLow = 9;  mMultHi = 10; mMultBins = 1;  mEvents2Mix = 10; break;
      case 6:  mMultLow = 11; mMultHi = 45; mMultBins = 1;  mEvents2Mix = 10; break;
      default: mMultLow = 0;  mMultHi = 45; mMultBins = 6;  mEvents2Mix = 10; break;
      };
    
      switch(iCharge) {
      case 0:   mLocalCharge = mPosCharge;    break;
      default:  mLocalCharge = mNegCharge;    break;
      };
      
      //
      // Create event cut
      //
      mPionEventCut[iCharge][iMult] = new gregsEventCut(*mBasicEventCut);
      mPionEventCut[iCharge][iMult]->SetEventMult(mMultLow, mMultHi);
#ifdef MONITORS
      mFxtPionEventCutMonitorPass[iCharge][iMult] = 
	new fxtEventCutMonitor("eventPionPass", Form("_%d_%d", iCharge, iMult));
      mFxtPionEventCutMonitorFail[iCharge][iMult] = 
	new fxtEventCutMonitor("eventPionFail", Form("_%d_%d", iCharge, iMult));
      mPionEventCut[iCharge][iMult]->AddCutMonitor(mFxtPionEventCutMonitorPass[iCharge][iMult],
						   mFxtPionEventCutMonitorFail[iCharge][iMult]);
#endif

	//                                 
	//  Like-sign pion analysis  
	//                               
	// create analysis
	mPionMultAnalysis[iCharge][iMult] = new StHbtVertexMultAnalysis(mPrimVertZbins,
									mPrimVertZ[0],
									mPrimVertZ[1],
									mMultBins,
									mMultLow,
									mMultHi);

	mPionMultAnalysis[iCharge][iMult]->SetEventCut(mPionEventCut[iCharge][iMult]);

	//
	// Create single-track cuts and add them to the analysis
	//
	mPionTrackCut[iCharge][iMult] = new gregsSimpleTrackCut(*mBasicTrackCut);
	mPionTrackCut[iCharge][iMult]->SetMass(mChargedPionMass);
	mPionTrackCut[iCharge][iMult]->SetCharge(mLocalCharge);
	mPionTrackCut[iCharge][iMult]->SetDetectorSelection(mCurrentPid);

	mPionTrackCut[iCharge][iMult]->SetTpcMomentum(0.15, 0.55);
	mPionTrackCut[iCharge][iMult]->SetNSigmaElectron(-1e9,1e9);
	mPionTrackCut[iCharge][iMult]->SetNSigmaPion(-2., 2.);
	mPionTrackCut[iCharge][iMult]->SetNSigmaKaon(-1e9, 1e9);
	mPionTrackCut[iCharge][iMult]->SetNSigmaProton(-1e9, 1e9);

	mPionTrackCut[iCharge][iMult]->SetTofMassSqr(-0.02, 0.062);
	mPionTrackCut[iCharge][iMult]->SetTofMomentum(0.15, 1.55);

	mPionTrackCut[iCharge][iMult]->SetTnTMomentum(0.15, 1.55);
	mPionTrackCut[iCharge][iMult]->SetTnTNSigmaElectron(-1e9, 1e9);
	mPionTrackCut[iCharge][iMult]->SetTnTNSigmaPion(-3., 3.);
	mPionTrackCut[iCharge][iMult]->SetTnTNSigmaKaon(-1e9, 1e9);
	mPionTrackCut[iCharge][iMult]->SetTnTNSigmaProton(-1e9, 1e9);

	mPionTrackCut[iCharge][iMult]->SetTTTMomentumThresh(0.45);

#ifdef MONITORS
	mFxtPionTrackCutMonitorPass[iCharge][iMult] = 
	  new fxtTrackCutMonitor(Form("_trackPionPass_%d_%d_", iCharge, iMult), mChargedPionMass);
	mFxtPionTrackCutMonitorFail[iCharge][iMult] = 
	  new fxtTrackCutMonitor(Form("_trackPionFail_%d_%d_", iCharge, iMult), mChargedPionMass);
	mPionTrackCut[iCharge][iMult]->AddCutMonitor(mFxtPionTrackCutMonitorPass[iCharge][iMult],
						     mFxtPionTrackCutMonitorFail[iCharge][iMult]);
#endif
	mPionMultAnalysis[iCharge][iMult]->SetFirstParticleCut(mPionTrackCut[iCharge][iMult]);
	mPionMultAnalysis[iCharge][iMult]->SetSecondParticleCut(mPionTrackCut[iCharge][iMult]);

	//
	// Create pair cut
	//
	mPionPairCut[iCharge][iMult] = new gregsTrackPairCut(*mBasicPairCut);
#ifdef MONITORS
	mFxtPionPairCutMonitorPass[iCharge][iMult] = 
	  new fxtPairCutMonitor(Form("_pairPionPass_%d_%d_", iCharge, iMult));
	mFxtPionPairCutMonitorPass[iCharge][iMult]->SetParticleMass(mChargedPionMass);
	mFxtPionPairCutMonitorFail[iCharge][iMult] = 
	  new fxtPairCutMonitor(Form("_pairPionFail_%d_%d_", iCharge, iMult));
	mFxtPionPairCutMonitorFail[iCharge][iMult]->SetParticleMass(mChargedPionMass);
	mPionPairCut[iCharge][iMult]->AddCutMonitor(mFxtPionPairCutMonitorPass[iCharge][iMult],
						    mFxtPionPairCutMonitorFail[iCharge][iMult]);
#endif
	mPionMultAnalysis[iCharge][iMult]->SetPairCut(mPionPairCut[iCharge][iMult]);

	//
	// Correlation function initialization
	//
	if (iMult == 0) {
	  mPionQinvMixKtCF[iCharge] = 
	    new QinvCorrFctnKt(Form("hPionQinvMixKt_%d", iCharge),
			       mQinvBins, mQinvVal[0], mQinvVal[1],
			       mPairKtBins, mPairKtVal[0], mPairKtVal[1]);
	  mPionQinvOppKtCF[iCharge] = 
	    new QinvCorrFctnOpposHemisphereKt(Form("hPionQinvOppKt_%d", iCharge),
					      mQinvBins, mQinvVal[0], mQinvVal[1],
					      mPairKtBins, mPairKtVal[0], mPairKtVal[1]);
	  mPionQinvRotKtCF[iCharge] = 
	    new QinvCorrFctnRotationKt(Form("hPionQinvRotKt_%d", iCharge),
				       mQinvBins, mQinvVal[0], mQinvVal[1],
				       mPairKtBins, mPairKtVal[0], mPairKtVal[1]);

	  mPionMultAnalysis[iCharge][iMult]->AddCorrFctn(mPionQinvMixKtCF[iCharge]);
	  mPionMultAnalysis[iCharge][iMult]->AddCorrFctn(mPionQinvOppKtCF[iCharge]);
	  mPionMultAnalysis[iCharge][iMult]->AddCorrFctn(mPionQinvRotKtCF[iCharge]);
	}
	mPionQinvMixMultCF[iCharge][iMult] = 
	  new QinvCorrFctn(Form("hPionQinvMixMult_%d_%d", iCharge, iMult),
			   mQinvBins, mQinvVal[0], mQinvVal[1]);
	mPionQinvOppMultCF[iCharge][iMult] = 
	  new QinvCorrFctnOpposHemisphere(Form("hPionQinvOppMult_%d_%d", iCharge, iMult),
					  mQinvBins, mQinvVal[0], mQinvVal[1]);
	mPionQinvRotMultCF[iCharge][iMult] = 
	  new QinvCorrFctnRotation(Form("hPionQinvRotMult_%d_%d", iCharge, iMult),
				   mQinvBins, mQinvVal[0], mQinvVal[1]);

	mPionMultAnalysis[iCharge][iMult]->AddCorrFctn(mPionQinvMixMultCF[iCharge][iMult]);
	mPionMultAnalysis[iCharge][iMult]->AddCorrFctn(mPionQinvOppMultCF[iCharge][iMult]);
	mPionMultAnalysis[iCharge][iMult]->AddCorrFctn(mPionQinvRotMultCF[iCharge][iMult]);
	
	mPionMultAnalysis[iCharge][iMult]->SetNumEventsToMix(mEvents2Mix); // set number of events to mix
	mHbtManager->AddAnalysis(mPionMultAnalysis[iCharge][iMult]); // add analysis to the manager
    } // for(Int_t iMult = 0; iMult < MULT_BINS; iMult++)
  } // for(Int_t iCharge = 0; iCharge < CHARGE_BINS; iCharge++)	


    
  mChain->Init(); // StChain initialization

  //
  // Start processing
  //
  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

  // mNEvents = 15;
  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 << "expMesonHBT_pp500_1D[ERROR] - iRet: " << iRet << std::endl;
      break;
    }
  }

  mChain->Finish();

  TFile *oFile = new TFile(oFileName, "RECREATE"); // create output file

  //
  // Write hbt histograms to the file
  //
  std::cout << "Writing histograms to the output file...";

#ifdef MONITORS
  for(Int_t iCharge = 0; iCharge < CHARGE_BINS; iCharge++) {  
    for(Int_t iMult = 0; iMult < MULT_BINS; iMult++) {  
      mFxtPionEventCutMonitorPass[iCharge][iMult]->VertexZ()->Write();
      mFxtPionEventCutMonitorPass[iCharge][iMult]->VertexYvsVertexX()->Write();
      mFxtPionEventCutMonitorPass[iCharge][iMult]->RefMult()->Write();
      mFxtPionEventCutMonitorPass[iCharge][iMult]->VpdVzDiff()->Write();
      mFxtPionEventCutMonitorFail[iCharge][iMult]->VertexZ()->Write();
      mFxtPionEventCutMonitorFail[iCharge][iMult]->VertexYvsVertexX()->Write();
      mFxtPionEventCutMonitorFail[iCharge][iMult]->RefMult()->Write();
      mFxtPionEventCutMonitorFail[iCharge][iMult]->VpdVzDiff()->Write();
      mFxtPionTrackCutMonitorPass[iCharge][iMult]->DCAGlobal()->Write();
      mFxtPionTrackCutMonitorPass[iCharge][iMult]->Nhits()->Write();
      mFxtPionTrackCutMonitorPass[iCharge][iMult]->P()->Write();
      mFxtPionTrackCutMonitorPass[iCharge][iMult]->Pt()->Write();
      mFxtPionTrackCutMonitorPass[iCharge][iMult]->PtVsNsigmaPion()->Write();
      mFxtPionTrackCutMonitorPass[iCharge][iMult]->PtVsNsigmaKaon()->Write();
      mFxtPionTrackCutMonitorPass[iCharge][iMult]->PtVsNsigmaProton()->Write();
      mFxtPionTrackCutMonitorPass[iCharge][iMult]->PvsDedx()->Write();
      mFxtPionTrackCutMonitorPass[iCharge][iMult]->Rapidity()->Write();
      mFxtPionTrackCutMonitorPass[iCharge][iMult]->PseudoRapidity()->Write();
      mFxtPionTrackCutMonitorPass[iCharge][iMult]->PtVsMassSqr()->Write();
      mFxtPionTrackCutMonitorFail[iCharge][iMult]->DCAGlobal()->Write();
      mFxtPionTrackCutMonitorFail[iCharge][iMult]->Nhits()->Write();
      mFxtPionTrackCutMonitorFail[iCharge][iMult]->P()->Write();
      mFxtPionTrackCutMonitorFail[iCharge][iMult]->Pt()->Write();
      mFxtPionTrackCutMonitorFail[iCharge][iMult]->PtVsNsigmaPion()->Write();
      mFxtPionTrackCutMonitorFail[iCharge][iMult]->PtVsNsigmaKaon()->Write();
      mFxtPionTrackCutMonitorFail[iCharge][iMult]->PtVsNsigmaProton()->Write();
      mFxtPionTrackCutMonitorFail[iCharge][iMult]->PvsDedx()->Write();
      mFxtPionTrackCutMonitorFail[iCharge][iMult]->Rapidity()->Write();
      mFxtPionTrackCutMonitorFail[iCharge][iMult]->PseudoRapidity()->Write();
      mFxtPionTrackCutMonitorFail[iCharge][iMult]->PtVsMassSqr()->Write();

      mFxtPionPairCutMonitorPass[iCharge][iMult]->Kt()->Write();
      mFxtPionPairCutMonitorPass[iCharge][iMult]->Pt1Pt2Qinv()->Write();
      mFxtPionPairCutMonitorPass[iCharge][iMult]->FMRvsQinv()->Write();
      mFxtPionPairCutMonitorPass[iCharge][iMult]->SLvsQinv()->Write();
      mFxtPionPairCutMonitorPass[iCharge][iMult]->AveSepVsQinv()->Write();
      mFxtPionPairCutMonitorFail[iCharge][iMult]->Kt()->Write();
      mFxtPionPairCutMonitorFail[iCharge][iMult]->Pt1Pt2Qinv()->Write();
      mFxtPionPairCutMonitorFail[iCharge][iMult]->FMRvsQinv()->Write();
      mFxtPionPairCutMonitorFail[iCharge][iMult]->SLvsQinv()->Write();
      mFxtPionPairCutMonitorFail[iCharge][iMult]->AveSepVsQinv()->Write();
    } // for(Int_t iMult = 0; iMult < MULT_BINS; iMult++)      
  } // for(Int_t iCharge = 0; iCharge < CHARGE_BINS; iCharge++)

    
#endif
  for(Int_t iMult = 0; iMult < MULT_BINS; iMult++) {
    for(Int_t iCharge = 0; iCharge < CHARGE_BINS; iCharge++) {
      if (iMult == 0) {
	for(Int_t iKt = 0; iKt < mPairKtBins; iKt++) {
	  mPionQinvMixKtCF[iCharge]->Numerator(iKt)->Write();
	  mPionQinvMixKtCF[iCharge]->Denominator(iKt)->Write();
	  mPionQinvOppKtCF[iCharge]->Numerator(iKt)->Write();
	  mPionQinvOppKtCF[iCharge]->Denominator(iKt)->Write();
	  mPionQinvRotKtCF[iCharge]->Numerator(iKt)->Write();
	  mPionQinvRotKtCF[iCharge]->Denominator(iKt)->Write();
	} // for(Int_t iKt = 0; iKt < mPairKtBins; iKt++)
      } // if (iMult == 0)
      mPionQinvMixMultCF[iCharge][iMult]->Numerator()->Write();
      mPionQinvMixMultCF[iCharge][iMult]->Denominator()->Write();
      mPionQinvOppMultCF[iCharge][iMult]->Numerator()->Write();
      mPionQinvOppMultCF[iCharge][iMult]->Denominator()->Write();
      mPionQinvRotMultCF[iCharge][iMult]->Numerator()->Write();
      mPionQinvRotMultCF[iCharge][iMult]->Denominator()->Write();
    } // for(Int_t iCharge = 0; iCharge < CHARGE_BINS; iCharge++)
  } // for(Int_t iMult = 0; iMult < MULT_BINS; iMult++)
  
  std::cout << "\t[DONE]" << std::endl;

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

  delete mChain;

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