#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 4
#define CHARGE_BINS 2

//
//  Event information
//
const int mPrimVertZbins = 6;                // number of z bins for analysis
const double mPrimVertZ[2] = {-50., 50.};    // 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] = {5, 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.;
const double mTrackMom[2] = {0.15, 1.55};        // general momentum of the track [GeV/c]
const double mTrackTransvMom[2] = {0.05, 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] = {-1e9, 1e9};
const double mnSigmaKaon[2] = {-2., 2.};
const double mnSigmaProton[2] = {-1e9, 1e9};

const double mTrackTofMom[2] = {0.15, 1.45};   // 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.2, 0.32};    // based on p+p data

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

const double mTTTMomThresh = 0.5; // 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., 0.8};         // 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., 1.6};          // redefine for each analysis

const Char_t *defaultInFile = "kaons.list";
const Char_t *defaultOutFile = "oExpKaon_pp200_1D.root";



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


  std::cout << "********************************" << std::endl
	    << "*       expKaonHBT_pp200_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(480004);      //Trigger selection for pp200 y2015 P16id VPDMB
  femtoReader->AddTrigId(480007);
  femtoReader->AddTrigId(480904);
  femtoReader->AddTrigId(470001); 
  femtoReader->AddTrigId(470004);
  femtoReader->AddTrigId(470007);
  femtoReader->AddTrigId(470014);
  femtoReader->AddTrigId(470017);
  femtoReader->AddTrigId(470904);
  femtoReader->AddTrigId(470914);
  femtoReader->AddTrigId(490004);
  femtoReader->AddTrigId(490007);
  femtoReader->AddTrigId(490904);
  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(mChargedKaonMass);
  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(mKaonTofMsqr[0],mKaonTofMsqr[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 *mKaonMultAnalysis[CHARGE_BINS][MULT_BINS]; // StHbtAnalysis, cut, CF and monitor declarations

  //
  // Cuts
  //
  gregsEventCut       *mKaonEventCut[CHARGE_BINS][MULT_BINS];
  gregsSimpleTrackCut *mKaonTrackCut[CHARGE_BINS][MULT_BINS];
  gregsTrackPairCut   *mKaonPairCut[CHARGE_BINS][MULT_BINS];

  //
  // CorrFctns
  //
  QinvCorrFctnKt                *mKaonQinvMixKtCF[CHARGE_BINS];
  QinvCorrFctnOpposHemisphereKt *mKaonQinvOppKtCF[CHARGE_BINS];
  QinvCorrFctnRotationKt        *mKaonQinvRotKtCF[CHARGE_BINS];
  QinvCorrFctn                  *mKaonQinvMixMultCF[CHARGE_BINS][MULT_BINS];
  QinvCorrFctnOpposHemisphere   *mKaonQinvOppMultCF[CHARGE_BINS][MULT_BINS];
  QinvCorrFctnRotation          *mKaonQinvRotMultCF[CHARGE_BINS][MULT_BINS];

#ifdef MONITORS
  //
  // Cut monitors
  //
  fxtEventCutMonitor *mFxtKaonEventCutMonitorPass[CHARGE_BINS][MULT_BINS];
  fxtTrackCutMonitor *mFxtKaonTrackCutMonitorPass[CHARGE_BINS][MULT_BINS];
  fxtPairCutMonitor  *mFxtKaonPairCutMonitorPass[CHARGE_BINS][MULT_BINS];
  fxtEventCutMonitor *mFxtKaonEventCutMonitorFail[CHARGE_BINS][MULT_BINS];
  fxtTrackCutMonitor *mFxtKaonTrackCutMonitorFail[CHARGE_BINS][MULT_BINS];
  fxtPairCutMonitor  *mFxtKaonPairCutMonitorFail[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 = 7;  mMultBins = 1;  mEvents2Mix = 10; break;
      case 2:  mMultLow = 8;  mMultHi = 11; mMultBins = 1;  mEvents2Mix = 10; break;
      case 3:  mMultLow = 12; mMultHi = 45; mMultBins = 1;  mEvents2Mix = 10; break;
      default: mMultLow = 0;  mMultHi = 45; mMultBins = 4;  mEvents2Mix = 10; break;
      };
    
      switch(iCharge) {
      case 0:   mLocalCharge = mPosCharge;    break;
      default:  mLocalCharge = mNegCharge;    break;
      };
      
      //
      // Create event cut
      //
      mKaonEventCut[iCharge][iMult] = new gregsEventCut(*mBasicEventCut);
      mKaonEventCut[iCharge][iMult]->SetEventMult(mMultLow, mMultHi);
#ifdef MONITORS
      mFxtKaonEventCutMonitorPass[iCharge][iMult] = 
	new fxtEventCutMonitor("eventKaonPass", Form("_%d_%d", iCharge, iMult));
      mFxtKaonEventCutMonitorFail[iCharge][iMult] = 
	new fxtEventCutMonitor("eventKaonFail", Form("_%d_%d", iCharge, iMult));
      mKaonEventCut[iCharge][iMult]->AddCutMonitor(mFxtKaonEventCutMonitorPass[iCharge][iMult],
						   mFxtKaonEventCutMonitorFail[iCharge][iMult]);
#endif

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

	mKaonMultAnalysis[iCharge][iMult]->SetEventCut(mKaonEventCut[iCharge][iMult]);

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

#ifdef MONITORS
	mFxtKaonTrackCutMonitorPass[iCharge][iMult] = 
	  new fxtTrackCutMonitor(Form("_trackKaonPass_%d_%d_", iCharge, iMult), mChargedKaonMass);
	mFxtKaonTrackCutMonitorFail[iCharge][iMult] = 
	  new fxtTrackCutMonitor(Form("_trackKaonFail_%d_%d_", iCharge, iMult), mChargedKaonMass);
	mKaonTrackCut[iCharge][iMult]->AddCutMonitor(mFxtKaonTrackCutMonitorPass[iCharge][iMult],
						     mFxtKaonTrackCutMonitorFail[iCharge][iMult]);
#endif
	mKaonMultAnalysis[iCharge][iMult]->SetFirstParticleCut(mKaonTrackCut[iCharge][iMult]);
	mKaonMultAnalysis[iCharge][iMult]->SetSecondParticleCut(mKaonTrackCut[iCharge][iMult]);

	//
	// Create pair cut
	//
	mKaonPairCut[iCharge][iMult] = new gregsTrackPairCut(*mBasicPairCut);
#ifdef MONITORS
	mFxtKaonPairCutMonitorPass[iCharge][iMult] = 
	  new fxtPairCutMonitor(Form("_pairKaonPass_%d_%d_", iCharge, iMult));
	mFxtKaonPairCutMonitorPass[iCharge][iMult]->SetParticleMass(mChargedKaonMass);
	mFxtKaonPairCutMonitorFail[iCharge][iMult] = 
	  new fxtPairCutMonitor(Form("_pairKaonFail_%d_%d_", iCharge, iMult));
	mFxtKaonPairCutMonitorFail[iCharge][iMult]->SetParticleMass(mChargedKaonMass);
	mKaonPairCut[iCharge][iMult]->AddCutMonitor(mFxtKaonPairCutMonitorPass[iCharge][iMult],
						    mFxtKaonPairCutMonitorFail[iCharge][iMult]);
#endif
	mKaonMultAnalysis[iCharge][iMult]->SetPairCut(mKaonPairCut[iCharge][iMult]);

	//
	// Correlation function initialization
	//
	if (iMult == 0) {
	  mKaonQinvMixKtCF[iCharge] = 
	    new QinvCorrFctnKt(Form("hKaonQinvMixKt_%d", iCharge),
			       mQinvBins, mQinvVal[0], mQinvVal[1],
			       mPairKtBins, mPairKtVal[0], mPairKtVal[1]);
	  mKaonQinvOppKtCF[iCharge] = 
	    new QinvCorrFctnOpposHemisphereKt(Form("hKaonQinvOppKt_%d", iCharge),
					      mQinvBins, mQinvVal[0], mQinvVal[1],
					      mPairKtBins, mPairKtVal[0], mPairKtVal[1]);
	  mKaonQinvRotKtCF[iCharge] = 
	    new QinvCorrFctnRotationKt(Form("hKaonQinvRotKt_%d", iCharge),
				       mQinvBins, mQinvVal[0], mQinvVal[1],
				       mPairKtBins, mPairKtVal[0], mPairKtVal[1]);

	  mKaonMultAnalysis[iCharge][iMult]->AddCorrFctn(mKaonQinvMixKtCF[iCharge]);
	  mKaonMultAnalysis[iCharge][iMult]->AddCorrFctn(mKaonQinvOppKtCF[iCharge]);
	  mKaonMultAnalysis[iCharge][iMult]->AddCorrFctn(mKaonQinvRotKtCF[iCharge]);
	}
	mKaonQinvMixMultCF[iCharge][iMult] = 
	  new QinvCorrFctn(Form("hKaonQinvMixMult_%d_%d", iCharge, iMult),
			   mQinvBins, mQinvVal[0], mQinvVal[1]);
	mKaonQinvOppMultCF[iCharge][iMult] = 
	  new QinvCorrFctnOpposHemisphere(Form("hKaonQinvOppMult_%d_%d", iCharge, iMult),
					  mQinvBins, mQinvVal[0], mQinvVal[1]);
	mKaonQinvRotMultCF[iCharge][iMult] = 
	  new QinvCorrFctnRotation(Form("hKaonQinvRotMult_%d_%d", iCharge, iMult),
				   mQinvBins, mQinvVal[0], mQinvVal[1]);

	mKaonMultAnalysis[iCharge][iMult]->AddCorrFctn(mKaonQinvMixMultCF[iCharge][iMult]);
	mKaonMultAnalysis[iCharge][iMult]->AddCorrFctn(mKaonQinvOppMultCF[iCharge][iMult]);
	mKaonMultAnalysis[iCharge][iMult]->AddCorrFctn(mKaonQinvRotMultCF[iCharge][iMult]);
	
	mKaonMultAnalysis[iCharge][iMult]->SetNumEventsToMix(mEvents2Mix); // set number of events to mix
	mHbtManager->AddAnalysis(mKaonMultAnalysis[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;
  std::cout << "Total Events: " << mNEvents << std::endl;
  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++) {  
      mFxtKaonEventCutMonitorPass[iCharge][iMult]->VertexZ()->Write();
      mFxtKaonEventCutMonitorPass[iCharge][iMult]->VertexYvsVertexX()->Write();
      mFxtKaonEventCutMonitorPass[iCharge][iMult]->RefMult()->Write();
      mFxtKaonEventCutMonitorPass[iCharge][iMult]->VpdVzDiff()->Write();
      mFxtKaonEventCutMonitorFail[iCharge][iMult]->VertexZ()->Write();
      mFxtKaonEventCutMonitorFail[iCharge][iMult]->VertexYvsVertexX()->Write();
      mFxtKaonEventCutMonitorFail[iCharge][iMult]->RefMult()->Write();
      mFxtKaonEventCutMonitorFail[iCharge][iMult]->VpdVzDiff()->Write();
      mFxtKaonTrackCutMonitorPass[iCharge][iMult]->DCAGlobal()->Write();
      mFxtKaonTrackCutMonitorPass[iCharge][iMult]->Nhits()->Write();
      mFxtKaonTrackCutMonitorPass[iCharge][iMult]->P()->Write();
      mFxtKaonTrackCutMonitorPass[iCharge][iMult]->Pt()->Write();
      mFxtKaonTrackCutMonitorPass[iCharge][iMult]->PtVsNsigmaPion()->Write();
      mFxtKaonTrackCutMonitorPass[iCharge][iMult]->PtVsNsigmaKaon()->Write();
      mFxtKaonTrackCutMonitorPass[iCharge][iMult]->PtVsNsigmaProton()->Write();
      mFxtKaonTrackCutMonitorPass[iCharge][iMult]->PvsDedx()->Write();
      mFxtKaonTrackCutMonitorPass[iCharge][iMult]->Rapidity()->Write();
      mFxtKaonTrackCutMonitorPass[iCharge][iMult]->PseudoRapidity()->Write();
      mFxtKaonTrackCutMonitorPass[iCharge][iMult]->PtVsMassSqr()->Write();
      mFxtKaonTrackCutMonitorFail[iCharge][iMult]->DCAGlobal()->Write();
      mFxtKaonTrackCutMonitorFail[iCharge][iMult]->Nhits()->Write();
      mFxtKaonTrackCutMonitorFail[iCharge][iMult]->P()->Write();
      mFxtKaonTrackCutMonitorFail[iCharge][iMult]->Pt()->Write();
      mFxtKaonTrackCutMonitorFail[iCharge][iMult]->PtVsNsigmaPion()->Write();
      mFxtKaonTrackCutMonitorFail[iCharge][iMult]->PtVsNsigmaKaon()->Write();
      mFxtKaonTrackCutMonitorFail[iCharge][iMult]->PtVsNsigmaProton()->Write();
      mFxtKaonTrackCutMonitorFail[iCharge][iMult]->PvsDedx()->Write();
      mFxtKaonTrackCutMonitorFail[iCharge][iMult]->Rapidity()->Write();
      mFxtKaonTrackCutMonitorFail[iCharge][iMult]->PseudoRapidity()->Write();
      mFxtKaonTrackCutMonitorFail[iCharge][iMult]->PtVsMassSqr()->Write();

      mFxtKaonPairCutMonitorPass[iCharge][iMult]->Kt()->Write();
      mFxtKaonPairCutMonitorPass[iCharge][iMult]->Pt1Pt2Qinv()->Write();
      mFxtKaonPairCutMonitorPass[iCharge][iMult]->FMRvsQinv()->Write();
      mFxtKaonPairCutMonitorPass[iCharge][iMult]->SLvsQinv()->Write();
      mFxtKaonPairCutMonitorPass[iCharge][iMult]->AveSepVsQinv()->Write();
      mFxtKaonPairCutMonitorFail[iCharge][iMult]->Kt()->Write();
      mFxtKaonPairCutMonitorFail[iCharge][iMult]->Pt1Pt2Qinv()->Write();
      mFxtKaonPairCutMonitorFail[iCharge][iMult]->FMRvsQinv()->Write();
      mFxtKaonPairCutMonitorFail[iCharge][iMult]->SLvsQinv()->Write();
      mFxtKaonPairCutMonitorFail[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++) {
	  mKaonQinvMixKtCF[iCharge]->Numerator(iKt)->Write();
	  mKaonQinvMixKtCF[iCharge]->Denominator(iKt)->Write();
	  mKaonQinvOppKtCF[iCharge]->Numerator(iKt)->Write();
	  mKaonQinvOppKtCF[iCharge]->Denominator(iKt)->Write();
	  mKaonQinvRotKtCF[iCharge]->Numerator(iKt)->Write();
	  mKaonQinvRotKtCF[iCharge]->Denominator(iKt)->Write();
	} // for(Int_t iKt = 0; iKt < mPairKtBins; iKt++)
      } // if (iMult == 0)
      mKaonQinvMixMultCF[iCharge][iMult]->Numerator()->Write();
      mKaonQinvMixMultCF[iCharge][iMult]->Denominator()->Write();
      mKaonQinvOppMultCF[iCharge][iMult]->Numerator()->Write();
      mKaonQinvOppMultCF[iCharge][iMult]->Denominator()->Write();
      mKaonQinvRotMultCF[iCharge][iMult]->Numerator()->Write();
      mKaonQinvRotMultCF[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
	    << "*       expKaonHBT_pp200_1D    *" << std::endl
	    << "*              Finish          *" << std::endl
	    << "********************************" << std::endl << std::endl;
}
