int main(int argc, char *argv[])
{
  cout.setf(ios::fixed, ios::floatfield);
  cout.precision(12);
  TH1::AddDirectory(kFALSE);

  cout << "Run " << argv[1] << " ..." << endl;

  char tempOut[500];
  sprintf(tempOut, "%s/replay_pass1_%s.root",getenv("REPLAY_PASS1"), argv[1]);
  


  //Check if the file is good already and quit if it is so that we can 
  // only replay the files that are bad...

  if ( OnlyReplayBadFiles ) {
     
    if ( checkIfReplayFileIsGood(std::string(tempOut)) == 1 ) return 1;
  
    else {
      std::ofstream badRuns("badRuns.txt", std::fstream::app);
      badRuns << argv[1] << "\n";
      badRuns.close();
    }
  }



  // Read cuts file
  char tempFileCuts[500];
  sprintf(tempFileCuts, "%s/cuts_%s.dat", getenv("CUTS"),argv[1]);
  cout << "... Reading: " << tempFileCuts << endl;

  ifstream fileCuts(tempFileCuts);
  fileCuts >> cutBeamBurstTime >> comment;
  fileCuts >> nCutsTimeWindows >> comment;
  if (nCutsTimeWindows > 0) {
    for (int i=0; i<nCutsTimeWindows; i++) {
      fileCuts >> cutTimeWindowLower[i] >> cutTimeWindowUpper[i];
    }
  }
  fileCuts >> cutEastAnode >> comment;
  fileCuts >> cutWestAnode >> comment;
  fileCuts >> cutEastTwoFold >> comment;
  fileCuts >> cutWestTwoFold >> comment;
  fileCuts >> cutEastTopVetoQADC >> comment;
  fileCuts >> cutEastTopVetoTDC >> comment;
  fileCuts >> cutEastDriftTubeTAC >> comment;
  fileCuts >> cutWestDriftTubeTAC >> comment;
  fileCuts >> cutEastBackingVetoQADC >> comment;
  fileCuts >> cutEastBackingVetoTDC >> comment;
  fileCuts >> cutWestBackingVetoQADC >> comment;
  fileCuts >> cutWestBackingVetoTDC >> comment;

  cout << "... Beam Burst T0 Cut: " << cutBeamBurstTime << endl;
  cout << "... Number of Time Windows Cuts: " << nCutsTimeWindows << endl;
  if (nCutsTimeWindows > 0) {
    for (int i=0; i<nCutsTimeWindows; i++) {
      cout << "        [" << cutTimeWindowLower[i] << ", " << cutTimeWindowUpper[i] << "]" << endl;
    }
  }
  cout << "... East MWPC Anode Cut: " << cutEastAnode << endl;
  cout << "... West MWPC Anode Cut: " << cutWestAnode << endl;
  cout << "... East Scintillator Two-Fold Trigger Cut: " << cutEastTwoFold << endl;
  cout << "... West Scintillator Two-Fold Trigger Cut: " << cutWestTwoFold << endl;
  cout << "... East Top Veto QADC Cut: " << cutEastTopVetoQADC << endl;
  cout << "... East Top Veto TDC Cut: " << cutEastTopVetoTDC << endl;
  cout << "... East Drift Tube TAC Cut: " << cutEastDriftTubeTAC << endl;
  cout << "... West Drift Tube TAC Cut: " << cutWestDriftTubeTAC << endl;
  cout << "... East Backing Veto QADC Cut: " << cutEastBackingVetoQADC << endl;
  cout << "... East Backing Veto TDC Cut: " << cutEastBackingVetoTDC << endl;
  cout << "... West Backing Veto QADC Cut: " << cutWestBackingVetoQADC << endl;
  cout << "... West Backing Veto TDC Cut: " << cutWestBackingVetoTDC << endl;

  //First load separate PMT pedestals as produced by the trigger thresholds

  std::vector < std::vector <Double_t> > pmtPedestals = loadPMTpedestals(atoi(argv[1]));
  

  // Read pedestals file
  char tempFilePed[500];
  int iRun;
  sprintf(tempFilePed, "%s/pedestals_%s.dat", getenv("PEDESTALS"), argv[1]);
  cout << "... Reading: " << tempFilePed << endl;

  ifstream filePed(tempFilePed);
  for (int i=0; i<8; i++) {
    filePed >> iRun >> pedQadc[i];   
    pedQadc[i] = pmtPedestals[i][0]; //replace pedQadc[i] with the pedestals separately loaded
  }
  for (int i=0; i<32; i++) {
    filePed >> iRun >> pedPdc2[i];
  }
  for (int i=0; i<32; i++) {
    filePed >> iRun >> pedPadc[i];
  }

  
  filePed >> iRun >> pedPdc30;
  filePed >> iRun >> pedPdc34;

  

  //cout << iRun << " " << pedPdc30 << endl;
  //cout << iRun << " " << pedPdc34 << endl;
  
  // Open output ntuple


  DataTree *t = new DataTree();
  t->makeOutputTree(std::string(tempOut),"pass1");  
  
  
  // Open input ntuple
  char tempIn[500];
  sprintf(tempIn, "%s/full%s.root",getenv("UCNA_RAW_DATA"), argv[1]);

  TFile *fileIn = new TFile(tempIn, "READ");
  TTree *Tin = (TTree*)(fileIn->Get("h1"));

  // Variables
  Tin->SetBranchAddress("Pdc30",  &Pdc30);
  Tin->SetBranchAddress("Pdc34",  &Pdc34);

  Tin->SetBranchAddress("Tdc016", &Tdc016);
  Tin->SetBranchAddress("Tdc017", &Tdc017);
  Tin->SetBranchAddress("Tdc00", &Tdc00);
  Tin->SetBranchAddress("Tdc01", &Tdc01);
  Tin->SetBranchAddress("Tdc02", &Tdc02);
  Tin->SetBranchAddress("Tdc03", &Tdc03);
  Tin->SetBranchAddress("Tdc08", &Tdc08);
  Tin->SetBranchAddress("Tdc09", &Tdc09);
  Tin->SetBranchAddress("Tdc014", &Tdc010); //Note that what used to be TDC10 is now TDC14
  Tin->SetBranchAddress("Tdc011", &Tdc011);

  Tin->SetBranchAddress("Sis00",  &Sis00);

  Tin->SetBranchAddress("Qadc0",  &Qadc[0]);
  Tin->SetBranchAddress("Qadc1",  &Qadc[1]);
  Tin->SetBranchAddress("Qadc2",  &Qadc[2]);
  Tin->SetBranchAddress("Qadc3",  &Qadc[3]);
  Tin->SetBranchAddress("Qadc4",  &Qadc[4]);
  Tin->SetBranchAddress("Qadc5",  &Qadc[5]);
  Tin->SetBranchAddress("Qadc6",  &Qadc[6]);
  Tin->SetBranchAddress("Qadc7",  &Qadc[7]);

  Tin->SetBranchAddress("Pdc20",  &Pdc2[0]);
  Tin->SetBranchAddress("Pdc21",  &Pdc2[1]);
  Tin->SetBranchAddress("Pdc22",  &Pdc2[2]);
  Tin->SetBranchAddress("Pdc23",  &Pdc2[3]);
  Tin->SetBranchAddress("Pdc24",  &Pdc2[4]);
  Tin->SetBranchAddress("Pdc25",  &Pdc2[5]);
  Tin->SetBranchAddress("Pdc26",  &Pdc2[6]);
  Tin->SetBranchAddress("Pdc27",  &Pdc2[7]);
  Tin->SetBranchAddress("Pdc28",  &Pdc2[8]);
  Tin->SetBranchAddress("Pdc29",  &Pdc2[9]);
  Tin->SetBranchAddress("Pdc210", &Pdc2[10]);
  Tin->SetBranchAddress("Pdc211", &Pdc2[11]);
  Tin->SetBranchAddress("Pdc212", &Pdc2[12]);
  Tin->SetBranchAddress("Pdc213", &Pdc2[13]);
  Tin->SetBranchAddress("Pdc214", &Pdc2[14]);
  Tin->SetBranchAddress("Pdc215", &Pdc2[15]);
  Tin->SetBranchAddress("Pdc216", &Pdc2[16]);
  Tin->SetBranchAddress("Pdc217", &Pdc2[17]);
  Tin->SetBranchAddress("Pdc218", &Pdc2[18]);
  Tin->SetBranchAddress("Pdc219", &Pdc2[19]);
  Tin->SetBranchAddress("Pdc220", &Pdc2[20]);
  Tin->SetBranchAddress("Pdc221", &Pdc2[21]);
  Tin->SetBranchAddress("Pdc222", &Pdc2[22]);
  Tin->SetBranchAddress("Pdc223", &Pdc2[23]);
  Tin->SetBranchAddress("Pdc224", &Pdc2[24]);
  Tin->SetBranchAddress("Pdc225", &Pdc2[25]);
  Tin->SetBranchAddress("Pdc226", &Pdc2[26]);
  Tin->SetBranchAddress("Pdc227", &Pdc2[27]);
  Tin->SetBranchAddress("Pdc228", &Pdc2[28]);
  Tin->SetBranchAddress("Pdc229", &Pdc2[29]);
  Tin->SetBranchAddress("Pdc230", &Pdc2[30]);
  Tin->SetBranchAddress("Pdc231", &Pdc2[31]);

  Tin->SetBranchAddress("Padc0",  &Padc[0]);
  Tin->SetBranchAddress("Padc1",  &Padc[1]);
  Tin->SetBranchAddress("Padc2",  &Padc[2]);
  Tin->SetBranchAddress("Padc3",  &Padc[3]);
  Tin->SetBranchAddress("Padc4",  &Padc[4]);
  Tin->SetBranchAddress("Padc5",  &Padc[5]);
  Tin->SetBranchAddress("Padc6",  &Padc[6]);
  Tin->SetBranchAddress("Padc7",  &Padc[7]);
  Tin->SetBranchAddress("Padc8",  &Padc[8]);
  Tin->SetBranchAddress("Padc9",  &Padc[9]);
  Tin->SetBranchAddress("Padc10", &Padc[10]);
  Tin->SetBranchAddress("Padc11", &Padc[11]);
  Tin->SetBranchAddress("Padc12", &Padc[12]);
  Tin->SetBranchAddress("Padc13", &Padc[13]);
  Tin->SetBranchAddress("Padc14", &Padc[14]);
  Tin->SetBranchAddress("Padc15", &Padc[15]);
  Tin->SetBranchAddress("Padc16", &Padc[16]);
  Tin->SetBranchAddress("Padc17", &Padc[17]);
  Tin->SetBranchAddress("Padc18", &Padc[18]);
  Tin->SetBranchAddress("Padc19", &Padc[19]);
  Tin->SetBranchAddress("Padc20", &Padc[20]);
  Tin->SetBranchAddress("Padc21", &Padc[21]);
  Tin->SetBranchAddress("Padc22", &Padc[22]);
  Tin->SetBranchAddress("Padc23", &Padc[23]);
  Tin->SetBranchAddress("Padc24", &Padc[24]);
  Tin->SetBranchAddress("Padc25", &Padc[25]);
  Tin->SetBranchAddress("Padc26", &Padc[26]);
  Tin->SetBranchAddress("Padc27", &Padc[27]);
  Tin->SetBranchAddress("Padc28", &Padc[28]);
  Tin->SetBranchAddress("Padc29", &Padc[29]);
  Tin->SetBranchAddress("Padc30", &Padc[30]);
  Tin->SetBranchAddress("Padc31", &Padc[31]);

  Tin->SetBranchAddress("S83028", &S83028);
  Tin->SetBranchAddress("S8200", &S8200);
  Tin->SetBranchAddress("Clk0", &Clk0);
  Tin->SetBranchAddress("Clk1", &Clk1);
  Tin->SetBranchAddress("Clk2", &Clk2);
  Tin->SetBranchAddress("Clk3", &Clk3);

  Tin->SetBranchAddress("Pdc38",  &Pdc38);
  Tin->SetBranchAddress("Pdc39",  &Pdc39);
  Tin->SetBranchAddress("Pdc310", &Pdc310);
  Tin->SetBranchAddress("Pdc311", &Pdc311);

  Tin->SetBranchAddress("Qadc9",  &Qadc9);
  Tin->SetBranchAddress("Tdc019", &Tdc019);
  Tin->SetBranchAddress("Pdc313", &Pdc313);
  Tin->SetBranchAddress("Pdc315", &Pdc315);
  Tin->SetBranchAddress("Qadc8",  &Qadc8);
  Tin->SetBranchAddress("Tdc018", &Tdc018);
  Tin->SetBranchAddress("Qadc10", &Qadc10);
  Tin->SetBranchAddress("Tdc020", &Tdc020);

  Tin->SetBranchAddress("Number", &Number);
  Tin->SetBranchAddress("Delt0", &Delt0);

  Tin->SetBranchAddress("Evnb0", &Evnb[0]);
  Tin->SetBranchAddress("Evnb1", &Evnb[1]);
  Tin->SetBranchAddress("Evnb2", &Evnb[2]);
  Tin->SetBranchAddress("Evnb3", &Evnb[3]);
  Tin->SetBranchAddress("Evnb4", &Evnb[4]);
  Tin->SetBranchAddress("Bkhf0", &Bkhf[0]);
  Tin->SetBranchAddress("Bkhf1", &Bkhf[1]);
  Tin->SetBranchAddress("Bkhf2", &Bkhf[2]);
  Tin->SetBranchAddress("Bkhf3", &Bkhf[3]);
  Tin->SetBranchAddress("Bkhf4", &Bkhf[4]);


  int nEvents = Tin->GetEntries();
  cout << "... Processing nEvents = " << nEvents << endl;

  //Get length of run from UNBLINDED TIME
  float runLengthBlind[2] = {0.};
  float runLengthTrue = 0.;
  Tin->GetEvent(nEvents-1);
  runLengthTrue = S83028*scalerCountsToTime;
  runLengthBlind[0] = Clk0*scalerCountsToTime;
  runLengthBlind[1] = Clk1*scalerCountsToTime;
  
  //Histograms to hold UCNMonRate
  int binWidth = 10;
  int nbins = (int)(runLengthTrue+20.)/binWidth;
  t->UCN_Mon_1_Rate = new TH1F("UCN_Mon_1_Rate","UCN Mon 1 Rate",nbins, 0., (float)nbins*binWidth);
  t->UCN_Mon_2_Rate = new TH1F("UCN_Mon_2_Rate","UCN Mon 2 Rate",nbins, 0., (float)nbins*binWidth);
  t->UCN_Mon_3_Rate = new TH1F("UCN_Mon_3_Rate","UCN Mon 3 Rate",nbins, 0., (float)nbins*binWidth);
  t->UCN_Mon_4_Rate = new TH1F("UCN_Mon_4_Rate","UCN Mon 4 Rate",nbins, 0., (float)nbins*binWidth);


  // Loop over events
  for (int i=0; i<nEvents; i++) {

    Tin->GetEvent(i);

    if ( i%10000==0 ) std::cout << i << std::endl;
    
    t->xE.nClipped = t->yE.nClipped = t->xW.nClipped = t->yW.nClipped = 0;

    Int_t iSis00 = (int) Sis00;

    // Calculate pedestal-subtracted PMT QADC values
    for (int j=0; j<8; j++) {
      pmt[j] = ((double) Qadc[j]) - pedQadc[j];
    }
    
    // Set cathode values to non-ped subtracted values
    for (int j=0; j<32; j++) {
      
      if (j<16) {
	t->Cathodes_Ey[j] = (double)Pdc2[j];
	t->Cathodes_Wy[j] = (double)Padc[j];
      }
      else {
	t->Cathodes_Ex[j-16] = (double)Pdc2[j];
	t->Cathodes_Wx[j-16] = (double)Padc[j];
      }
    }

    //////////////////////////////////////////////////////////
    // For making a max Cathode signal cut

    double CathMaxCut = 300.; // This is pedestal subtracted
    
    MWPCCathodeHandler cathResp(t->Cathodes_Ex,t->Cathodes_Ey,t->Cathodes_Wx,t->Cathodes_Wy,&pedPdc2[16],&pedPdc2[0],&pedPadc[16],&pedPadc[0]);
    
    //Get the max signal in each plane (ped subtracted)
    double cathMaxEX = cathResp.getMaxSignalEX();
    double cathMaxEY = cathResp.getMaxSignalEY();
    double cathMaxWX = cathResp.getMaxSignalWX();
    double cathMaxWY = cathResp.getMaxSignalWY();
    
    double maxCathSumE = cathMaxEX + cathMaxEY;
    double maxCathSumW = cathMaxWX + cathMaxWY;

    //Also saving one set of positions for making position maps
    cathResp.findAllPositions(true,false);

    
    std::vector<double> posex = cathResp.getPosEX();
    std::vector<double> posey = cathResp.getPosEY();
    std::vector<double> poswx = cathResp.getPosWX();
    std::vector<double> poswy = cathResp.getPosWY();
    
    t->xE.center = posex[0] * positionProjection;
    t->yE.center = posey[0] * positionProjection;
    t->xW.center = poswx[0] * positionProjection;
    t->yW.center = poswy[0] * positionProjection;
    
    t->xE.width = posex[1] * positionProjection;
    t->yE.width = posey[1] * positionProjection;
    t->xW.width = poswx[1] * positionProjection;
    t->yW.width = poswy[1] * positionProjection;
    
    t->xE.height = posex[2];
    t->yE.height = posey[2];
    t->xW.height = poswx[2];
    t->yW.height = poswy[2];
    
    t->xE.mult = cathResp.getMultEX();
    t->yE.mult = cathResp.getMultEY();
    t->xW.mult = cathResp.getMultWX();
    t->yW.mult = cathResp.getMultWY();
    
    t->xE.nClipped = cathResp.getnClippedEX();
    t->yE.nClipped = cathResp.getnClippedEY();
    t->xW.nClipped = cathResp.getnClippedWX();
    t->yW.nClipped = cathResp.getnClippedWY();
    
    t->xE.maxWire = cathResp.getMaxWireEX();
    t->yE.maxWire = cathResp.getMaxWireEY();
    t->xW.maxWire = cathResp.getMaxWireWX();
    t->yW.maxWire = cathResp.getMaxWireWY();
    
    t->xE.maxValue = cathResp.getMaxSignalEX();
    t->yE.maxValue = cathResp.getMaxSignalEY();
    t->xW.maxValue = cathResp.getMaxSignalWX();
    t->yW.maxValue = cathResp.getMaxSignalWY();
    
    t->xE.cathSum = cathResp.getCathSumEX();
    t->yE.cathSum = cathResp.getCathSumEY();
    t->xW.cathSum = cathResp.getCathSumWX();
    t->yW.cathSum = cathResp.getCathSumWY();
    
    t->CathSumE = t->xE.cathSum + t->yE.cathSum;
    t->CathSumW = t->xW.cathSum + t->yW.cathSum;
    
    t->CathMaxE = t->xE.maxValue + t->yE.maxValue;
    t->CathMaxW = t->xW.maxValue + t->yW.maxValue;
    
    t->xE.rawCenter = cathResp.getWirePosEX(t->xE.maxWire);
    t->yE.rawCenter = cathResp.getWirePosEY(t->yE.maxWire);
    t->xW.rawCenter = cathResp.getWirePosWX(t->xW.maxWire);
    t->yW.rawCenter = cathResp.getWirePosWY(t->yW.maxWire);

      

    ///////////////////////////////////////////////////////////
    
    
    // Calculate pedestal-subtracted MWPC Anode PADC values
    AnodeE = ((double) Pdc30) - pedPdc30;
    AnodeW = ((double) Pdc34) - pedPdc34;

    // UCN monitor events
    bool UCNMonitorTrigger = false;
    
    float time = S83028*scalerCountsToTime;
    if (iSis00==260) {t->UCN_Mon_1_Rate->Fill(time,1./binWidth); UCNMonitorTrigger = true;}
    else if (iSis00==516) {t->UCN_Mon_2_Rate->Fill(time,1./binWidth); UCNMonitorTrigger = true;}
    else if (iSis00==1028) {t->UCN_Mon_3_Rate->Fill(time,1./binWidth); UCNMonitorTrigger = true;}
    else if (iSis00==2052) {t->UCN_Mon_4_Rate->Fill(time,1./binWidth); UCNMonitorTrigger = true;}
    

    // Events with a muon hit
    bool muonHitEast = false;
    bool muonHitWest = false;
    if ( (((double) Qadc8)  > cutEastBackingVetoQADC) ||
         (((double) Tdc018) > cutEastBackingVetoTDC)  ||
         (((double) Qadc9)  > cutEastTopVetoQADC)     ||
         (((double) Tdc019) > cutEastTopVetoTDC)      ||
         (((double) Pdc313) > cutEastDriftTubeTAC) ) {
      muonHitEast = true;
    }
    if ( (((double) Qadc10) > cutWestBackingVetoQADC) ||
         (((double) Tdc020) > cutWestBackingVetoTDC)  ||
         (((double) Pdc315) > cutWestDriftTubeTAC) ) {
      muonHitWest = true;
    }
    
    t->TaggedBackE = (((double) Qadc8)  > cutEastBackingVetoQADC || ((double) Tdc018) > cutEastBackingVetoTDC)?true:false;
    t->TaggedBackW = (((double) Qadc10)  > cutWestBackingVetoQADC || ((double) Tdc020) > cutEastBackingVetoTDC)?true:false;
    t->TaggedTopE = (((double) Qadc9)  > cutEastTopVetoQADC || ((double) Tdc019) > cutEastTopVetoTDC)?true:false;
    t->TaggedTopW = false;
    t->TaggedDriftE = (((double) Pdc313)  > cutEastDriftTubeTAC)?true:false;
    t->TaggedDriftW = (((double) Pdc315)  > cutWestDriftTubeTAC)?true:false;

    t->EastBackADC = (double) Qadc8;
    t->WestBackADC = (double) Qadc10;
    t->EastBackTDC = (double) Tdc018;
    t->WestBackTDC = (double) Tdc020;
    t->EastDriftVetoADC = (double) Pdc313;
    t->WestDriftVetoADC = (double) Pdc315;
    t->EastTopVetoADC = (double) Qadc9;
    t->EastTopVetoTDC = (double) Tdc019;
    

    // LED trigger events
    bool LEDTrigger = false;
    if ( (iSis00 == 128) || (iSis00 == 129) || (iSis00 == 130) || (iSis00 == 131) || (iSis00 == 163) ) {
      LEDTrigger = true;
    }

    // Bi pulser trigger events
    bool bismuthPulser = false;
    if (iSis00 == 32) bismuthPulser = true;

    // Scintillator events
    bool mwpcHitEast = false;
    bool mwpcHitWest = false;
    bool scintillatorHitEast = false;
    bool scintillatorHitWest = false;
    bool scintillatorHitBoth = false;
    bool coincidenceEast = false;
    bool coincidenceWest = false;
    bool scintillatorHitFirstEast = false;
    bool scintillatorHitFirstWest = false;
    bool scintillatorHitBothBad = false;
    bool triggerEast = false;
    bool triggerWest = false;

    t->PassedAnoE = t->PassedAnoW = false;
    t->PassedCathE = t->PassedCathW = false;
    
    if ( ((double) Pdc30)  > cutEastAnode) { t->PassedAnoE=true; }
    if ( ((double) Pdc34)  > cutWestAnode) { t->PassedAnoW=true; }


    // Using the cathode sum of max wires to determine MWPC trigger
    if ( maxCathSumE > CathMaxCut ) { mwpcHitEast = true; t->PassedCathE=true; }
    if ( maxCathSumW > CathMaxCut ) { mwpcHitWest = true; t->PassedCathW=true; }

    double timeEastTwoFold = ((double) Tdc016)*tdcChannelToTime;
    double timeWestTwoFold = ((double) Tdc017)*tdcChannelToTime;
    if (timeEastTwoFold > 0.*tdcChannelToTime) scintillatorHitEast = true;
    if (timeWestTwoFold > 0.*tdcChannelToTime) scintillatorHitWest = true;
    if (scintillatorHitEast && scintillatorHitWest) {
      scintillatorHitBoth = true;
      if ( (timeEastTwoFold > cutEastTwoFold) && (timeWestTwoFold < cutWestTwoFold) ) {
        scintillatorHitFirstEast = true;
      }
      else if ( (timeEastTwoFold < cutEastTwoFold) && (timeWestTwoFold > cutWestTwoFold) ) {
        scintillatorHitFirstWest = true;
      }
      else if ( (timeEastTwoFold > cutEastTwoFold) && (timeWestTwoFold > cutWestTwoFold) ) {
        scintillatorHitBothBad = true;
      }
      else if ( (timeEastTwoFold < cutEastTwoFold) && (timeWestTwoFold < cutWestTwoFold) ) {
        scintillatorHitBothBad = true;
      }
    }

    if (mwpcHitEast && scintillatorHitEast) coincidenceEast = true;
    if (mwpcHitWest && scintillatorHitWest) coincidenceWest = true;


    // Event PID logic

    type = 4; //not an electron event
    side = 2; //No scintillator triggers

    if (UCNMonitorTrigger) PID = 5;
    else if (LEDTrigger) PID = 3;
    else if (muonHitEast || muonHitWest) PID = 2;
    else if (bismuthPulser) PID = 4;
    else if ( (scintillatorHitEast && !mwpcHitEast && !scintillatorHitWest && !mwpcHitWest) ||
              (!scintillatorHitEast && !mwpcHitEast && scintillatorHitWest && !mwpcHitWest) ) { PID = 0; side = scintillatorHitEast ? 0 : 1; }
    else if ( (coincidenceEast && !scintillatorHitWest && !mwpcHitWest) ||
              (!scintillatorHitEast && !mwpcHitEast && coincidenceWest) ||
              (coincidenceEast && coincidenceWest) ||
              (coincidenceEast && !scintillatorHitWest && mwpcHitWest) ||
              (!scintillatorHitEast && mwpcHitEast && coincidenceWest) ) PID = 1;
    else PID = 6;

    
    if (PID == 1) {
      if (coincidenceEast && !scintillatorHitWest && !mwpcHitWest) {
        type = 0;
        side = 0;
      }
      if (!scintillatorHitEast && !mwpcHitEast && coincidenceWest) {
        type = 0;
        side = 1;
      }
      if (coincidenceEast && coincidenceWest) {
        type = 1;
        if (scintillatorHitFirstEast) side = 0;
        if (scintillatorHitFirstWest) side = 1;
      }
      if (coincidenceEast && !scintillatorHitWest && mwpcHitWest) {
        type = 2;
        side = 0;
      }
      if (!scintillatorHitEast && mwpcHitEast && coincidenceWest) {
        type = 2;
        side = 1;
      }
    }

    

    
    //////////////////////////////////////////////////////////////////////////////////
    /*  Swank's addition to the UK PA.  (2 of 2)
	this seems like a good spot since its around the position calculation. 
    */

    int xeRC,yeRC,xwRC,ywRC;
    WireChamberResponse * WCR = new WireChamberResponse();

    //changing the length 32 double array to length 16  float array.  using variables defined in WCR. 
    for(int j = 0; j<16; j++)
      {
	WCR->cathex[j]=Pdc2[16+j];
	WCR->cathey[j]=Pdc2[j];
	WCR->cathwx[j]=Padc[16+j];
	WCR->cathwy[j]=Padc[j];
      } 
    
    xeRC=WCR->ResponseType(WCR->cathex);   //response class x co-ordinate, East. 
    yeRC=WCR->ResponseType(WCR->cathey);   //response class y co-ordinate, East. 
    xwRC=WCR->ResponseType(WCR->cathwx);   //response class x co-ordinate, West. 
    ywRC=WCR->ResponseType(WCR->cathwy);   //response class y co-ordinate, West.

    delete WCR;
    /*
      End of swank's addtion (2 of 2)
    */
    ////////////////////////////////////////////////////////////////////////////////////
    
    // Calculate MWPC positions for electron events
    
    
    // Pass Everything to output tree
    t->TriggerNum = (int) Number;
    t->EvtN = i;
    t->Sis00 = iSis00;
    t->DeltaT = ((double)Delt0)*scalerCountsToTime;
    t->Tof = (double) S8200;
    t->TimeE = Clk0*scalerCountsToTime;
    t->TimeW = Clk1*scalerCountsToTime;
    t->Time = S83028*scalerCountsToTime;
    t->badTimeFlag = 0;
    t->oldTimeE = Clk0*scalerCountsToTime;
    t->oldTimeW = Clk1*scalerCountsToTime;
    t->oldTime = S83028*scalerCountsToTime;
    t->TDCE = (double) Tdc016;
    t->TDCW = (double) Tdc017;
    t->TDCE1 = (double) Tdc00;
    t->TDCE2 = (double) Tdc01;
    t->TDCE3 = (double) Tdc02;
    t->TDCE4 = (double) Tdc03;
    t->TDCW1 = (double) Tdc08;
    t->TDCW2 = (double) Tdc09;
    t->TDCW3 = (double) Tdc010;
    t->TDCW4 = (double) Tdc011;
    
    //Wirechambers
    
    t->xE.err = 0.;
    t->xE.rawCenter = 0.;
      
    t->yE.err = 0.;
    t->yE.rawCenter = 0.;
   
    t->xW.err = 0.;
    t->xW.rawCenter = 0.;
   
    t->yW.err = 0.;
    t->yW.rawCenter = 0.;
    
    t->ScintE.q1 = pmt[0];
    t->ScintE.q2 = pmt[1];
    t->ScintE.q3 = pmt[2];
    t->ScintE.q4 = pmt[3]; 
    t->ScintE.e1=t->ScintE.de1=t->ScintE.e2=t->ScintE.de2=t->ScintE.e3=t->ScintE.de3=t->ScintE.e4=t->ScintE.de4=0.;
    t->ScintE.energy=t->ScintE.denergy=0.;
    t->ScintE.nPE1=t->ScintE.nPE2=t->ScintE.nPE3=t->ScintE.nPE4=0.;
    
    t->ScintW.q1 = pmt[4];
    t->ScintW.q2 = pmt[5];
    t->ScintW.q3 = pmt[6];
    t->ScintW.q4 = pmt[7]; 
    t->ScintW.e1=t->ScintW.de1=t->ScintW.e2=t->ScintW.de2=t->ScintW.e3=t->ScintW.de3=t->ScintW.e4=t->ScintW.de4=0.;
    t->ScintW.energy=t->ScintW.denergy=0.;
    t->ScintW.nPE1=t->ScintW.nPE2=t->ScintW.nPE3=t->ScintW.nPE4=0.;

    t->ScintE_bare.q1 = pmt[0];
    t->ScintE_bare.q2 = pmt[1];
    t->ScintE_bare.q3 = pmt[2];
    t->ScintE_bare.q4 = pmt[3]; 
    t->ScintE_bare.e1=t->ScintE_bare.de1=t->ScintE_bare.e2=t->ScintE_bare.de2=t->ScintE_bare.e3=t->ScintE_bare.de3=t->ScintE_bare.e4=t->ScintE_bare.de4=0.;
    t->ScintE_bare.energy=t->ScintE_bare.denergy=0.;
    t->ScintE_bare.nPE1=t->ScintE_bare.nPE2=t->ScintE_bare.nPE3=t->ScintE_bare.nPE4=0.;
    
    t->ScintW_bare.q1 = pmt[4];
    t->ScintW_bare.q2 = pmt[5];
    t->ScintW_bare.q3 = pmt[6];
    t->ScintW_bare.q4 = pmt[7]; 
    t->ScintW_bare.e1=t->ScintW_bare.de1=t->ScintW_bare.e2=t->ScintW_bare.de2=t->ScintW_bare.e3=t->ScintW_bare.de3=t->ScintW_bare.e4=t->ScintW_bare.de4=0.;
    t->ScintW_bare.energy=t->ScintW_bare.denergy=0.;
    t->ScintW_bare.nPE1=t->ScintW_bare.nPE2=t->ScintW_bare.nPE3=t->ScintW_bare.nPE4=0.;
    
    t->EvisE = t->EvisW = 0.;
    
    t->CathSumE =  t->xE.cathSum+t->yE.cathSum;
    t->CathSumW =  t->xW.cathSum+t->yW.cathSum;
    
    t->CathMaxE = (t->xE.maxValue>t->yE.maxValue)?t->yE.maxValue:t->xE.maxValue;
    t->CathMaxW = (t->xW.maxValue>t->yW.maxValue)?t->yW.maxValue:t->xW.maxValue;
    
    t->EMWPC_E = t->EMWPC_W = 0.;
    
    t->AnodeE = AnodeE; // Pedestal subtracted
    t->AnodeW = AnodeW;
    
    t->EvnbGood = t->BkhfGood = true;
    for (Int_t i = 0; i<5; i++) {
      if ((int)Evnb[i]-t->TriggerNum) t->EvnbGood = false;
      if ((int)Bkhf[i]!=17) t->BkhfGood = false;
    }
    
    t->xeRC = xeRC;
    t->yeRC = yeRC;
    t->xwRC = xwRC;
    t->ywRC = ywRC;
    
    t->PID = PID;
    t->Type = type;
    t->Side = side;
    t->ProbIII = 0.;
    t->Erecon = 0.;
    t->Erecon_ee = 0.;
    t->old_Erecon = 0.;
    t->gaus_Erecon = 0.;


      /*timeE_BB = Clk2*scalerCountsToTime;
      timeW_BB = Clk3*scalerCountsToTime;
      UBtime = S83028*scalerCountsToTime;
      UBtime_BB = S8200*scalerCountsToTime;
      twoFoldE = Tdc016;
      twoFoldW = Tdc017;*/
  
    t->fillOutputTree();
    
  }
  
  fileIn->Close();

  
  // Write output ntuple
  t->writeOutputFile();
  delete t;


  if ( checkIfReplayFileIsGood(std::string(tempOut)) != 1 ) {

    std::ofstream badRuns("badRuns.txt", std::fstream::app);
    badRuns << argv[1] << "\n";
    badRuns.close();

  }
  

  return 0;
}
int main(int argc, char *argv[])
{
  cout.setf(ios::fixed, ios::floatfield);
  cout.precision(12);
  TH1::AddDirectory(kFALSE);

  cout << "Run " << argv[1] << " ..." << endl;

  // Read cuts file
  char tempFileCuts[500];
  sprintf(tempFileCuts, "%s/cuts_%s.dat", getenv("CUTS"),argv[1]);
  cout << "... Reading: " << tempFileCuts << endl;

  ifstream fileCuts(tempFileCuts);
  fileCuts >> cutBeamBurstTime >> comment;
  fileCuts >> nCutsTimeWindows >> comment;
  if (nCutsTimeWindows > 0) {
    for (int i=0; i<nCutsTimeWindows; i++) {
      fileCuts >> cutTimeWindowLower[i] >> cutTimeWindowUpper[i];
    }
  }
  fileCuts >> cutEastAnode >> comment;
  fileCuts >> cutWestAnode >> comment;
  fileCuts >> cutEastTwoFold >> comment;
  fileCuts >> cutWestTwoFold >> comment;
  fileCuts >> cutEastTopVetoQADC >> comment;
  fileCuts >> cutEastTopVetoTDC >> comment;
  fileCuts >> cutEastDriftTubeTAC >> comment;
  fileCuts >> cutWestDriftTubeTAC >> comment;
  fileCuts >> cutEastBackingVetoQADC >> comment;
  fileCuts >> cutEastBackingVetoTDC >> comment;
  fileCuts >> cutWestBackingVetoQADC >> comment;
  fileCuts >> cutWestBackingVetoTDC >> comment;

  cout << "... Beam Burst T0 Cut: " << cutBeamBurstTime << endl;
  cout << "... Number of Time Windows Cuts: " << nCutsTimeWindows << endl;
  if (nCutsTimeWindows > 0) {
    for (int i=0; i<nCutsTimeWindows; i++) {
      cout << "        [" << cutTimeWindowLower[i] << ", " << cutTimeWindowUpper[i] << "]" << endl;
    }
  }
  cout << "... East MWPC Anode Cut: " << cutEastAnode << endl;
  cout << "... West MWPC Anode Cut: " << cutWestAnode << endl;
  cout << "... East Scintillator Two-Fold Trigger Cut: " << cutEastTwoFold << endl;
  cout << "... West Scintillator Two-Fold Trigger Cut: " << cutWestTwoFold << endl;
  cout << "... East Top Veto QADC Cut: " << cutEastTopVetoQADC << endl;
  cout << "... East Top Veto TDC Cut: " << cutEastTopVetoTDC << endl;
  cout << "... East Drift Tube TAC Cut: " << cutEastDriftTubeTAC << endl;
  cout << "... West Drift Tube TAC Cut: " << cutWestDriftTubeTAC << endl;
  cout << "... East Backing Veto QADC Cut: " << cutEastBackingVetoQADC << endl;
  cout << "... East Backing Veto TDC Cut: " << cutEastBackingVetoTDC << endl;
  cout << "... West Backing Veto QADC Cut: " << cutWestBackingVetoQADC << endl;
  cout << "... West Backing Veto TDC Cut: " << cutWestBackingVetoTDC << endl;

  

  // Read pedestals file
  char tempFilePed[500];
  int iRun;
  sprintf(tempFilePed, "%s/pedestals_%s.dat", getenv("PEDESTALS"), argv[1]);
  cout << "... Reading: " << tempFilePed << endl;

  ifstream filePed(tempFilePed);
  for (int i=0; i<8; i++) {
    filePed >> iRun >> pedQadc[i];
  }
  for (int i=0; i<32; i++) {
    filePed >> iRun >> pedPdc2[i];
  }
  for (int i=0; i<32; i++) {
    filePed >> iRun >> pedPadc[i];
  }
  //filePed >> iRun >> pedPdc30;
  //filePed >> iRun >> pedPdc34;

  //cout << iRun << " " << pedPdc30 << endl;
  //cout << iRun << " " << pedPdc34 << endl;
  
  // Open output ntuple
  char tempOut[500];
  sprintf(tempOut, "%s/replay_pass1_%s.root",getenv("REPLAY_PASS1"), argv[1]);
  //sprintf(tempOut, "replay_pass1_%s.root", argv[1]);
  DataTree t;// = new DataTree();
  t.makeOutputTree(std::string(tempOut),"pass1");  
  
  
  // East MWPC y                                                                  
  posPdc2[0]  =  76.20;
  posPdc2[1]  =  66.04;
  posPdc2[2]  =  55.88;
  posPdc2[3]  =  45.72;
  posPdc2[4]  =  35.56;
  posPdc2[5]  =  25.40;
  posPdc2[6]  =  15.24;
  posPdc2[7]  =   5.08;
  posPdc2[8]  =  -5.08;
  posPdc2[9]  = -15.24;
  posPdc2[10] = -25.40;
  posPdc2[11] = -35.56;
  posPdc2[12] = -45.72;
  posPdc2[13] = -55.88;
  posPdc2[14] = -66.04;
  posPdc2[15] = -76.20;

  // East MWPC x                                                                  
  posPdc2[16] =  76.20;
  posPdc2[17] =  66.04;
  posPdc2[18] =  55.88;
  posPdc2[19] =  45.72;
  posPdc2[20] =  35.56;
  posPdc2[21] =  25.40;
  posPdc2[22] =  15.24;
  posPdc2[23] =   5.08;
  posPdc2[24] =  -5.08;
  posPdc2[25] = -15.24;
  posPdc2[26] = -25.40;
  posPdc2[27] = -35.56;
  posPdc2[28] = -45.72;
  posPdc2[29] = -55.88;
  posPdc2[30] = -66.04;
  posPdc2[31] = -76.20;

  // West MWPC y                                                                  
  posPadc[0]  =  76.20;
  posPadc[1]  =  66.04;
  posPadc[2]  =  55.88;
  posPadc[3]  =  45.72;
  posPadc[4]  =  35.56;
  posPadc[5]  =  25.40;
  posPadc[6]  =  15.24;
  posPadc[7]  =   5.08;
  posPadc[8]  =  -5.08;
  posPadc[9]  = -15.24;
  posPadc[10] = -25.40;
  posPadc[11] = -35.56;
  posPadc[12] = -45.72;
  posPadc[13] = -55.88;
  posPadc[14] = -66.04;
  posPadc[15] = -76.20;

  // West MWPC x                                                                  
  posPadc[16] = -76.20;
  posPadc[17] = -66.04;
  posPadc[18] = -55.88;
  posPadc[19] = -45.72;
  posPadc[20] = -35.56;
  posPadc[21] = -25.40;
  posPadc[22] = -15.24;
  posPadc[23] =  -5.08;
  posPadc[24] =   5.08;
  posPadc[25] =  15.24;
  posPadc[26] =  25.40;
  posPadc[27] =  35.56;
  posPadc[28] =  45.72;
  posPadc[29] =  55.88;
  posPadc[30] =  66.04;
  posPadc[31] =  76.20;

  // Open input ntuple
  char tempIn[500];
  sprintf(tempIn, "/extern/mabrow05/ucna/rawdata/full%s.root", argv[1]);

  TFile *fileIn = new TFile(tempIn, "READ");
  TTree *Tin = (TTree*)(fileIn->Get("h1"));

  // Variables
  Tin->SetBranchAddress("Pdc30",  &Pdc30);
  Tin->SetBranchAddress("Pdc34",  &Pdc34);

  Tin->SetBranchAddress("Tdc016", &Tdc016);
  Tin->SetBranchAddress("Tdc017", &Tdc017);
  Tin->SetBranchAddress("Tdc00", &Tdc00);
  Tin->SetBranchAddress("Tdc01", &Tdc01);
  Tin->SetBranchAddress("Tdc02", &Tdc02);
  Tin->SetBranchAddress("Tdc03", &Tdc03);
  Tin->SetBranchAddress("Tdc08", &Tdc08);
  Tin->SetBranchAddress("Tdc09", &Tdc09);
  Tin->SetBranchAddress("Tdc010", &Tdc010);
  Tin->SetBranchAddress("Tdc011", &Tdc011);

  Tin->SetBranchAddress("Sis00",  &Sis00);

  Tin->SetBranchAddress("Qadc0",  &Qadc[0]);
  Tin->SetBranchAddress("Qadc1",  &Qadc[1]);
  Tin->SetBranchAddress("Qadc2",  &Qadc[2]);
  Tin->SetBranchAddress("Qadc3",  &Qadc[3]);
  Tin->SetBranchAddress("Qadc4",  &Qadc[4]);
  Tin->SetBranchAddress("Qadc5",  &Qadc[5]);
  Tin->SetBranchAddress("Qadc6",  &Qadc[6]);
  Tin->SetBranchAddress("Qadc7",  &Qadc[7]);

  Tin->SetBranchAddress("Pdc20",  &Pdc2[0]);
  Tin->SetBranchAddress("Pdc21",  &Pdc2[1]);
  Tin->SetBranchAddress("Pdc22",  &Pdc2[2]);
  Tin->SetBranchAddress("Pdc23",  &Pdc2[3]);
  Tin->SetBranchAddress("Pdc24",  &Pdc2[4]);
  Tin->SetBranchAddress("Pdc25",  &Pdc2[5]);
  Tin->SetBranchAddress("Pdc26",  &Pdc2[6]);
  Tin->SetBranchAddress("Pdc27",  &Pdc2[7]);
  Tin->SetBranchAddress("Pdc28",  &Pdc2[8]);
  Tin->SetBranchAddress("Pdc29",  &Pdc2[9]);
  Tin->SetBranchAddress("Pdc210", &Pdc2[10]);
  Tin->SetBranchAddress("Pdc211", &Pdc2[11]);
  Tin->SetBranchAddress("Pdc212", &Pdc2[12]);
  Tin->SetBranchAddress("Pdc213", &Pdc2[13]);
  Tin->SetBranchAddress("Pdc214", &Pdc2[14]);
  Tin->SetBranchAddress("Pdc215", &Pdc2[15]);
  Tin->SetBranchAddress("Pdc216", &Pdc2[16]);
  Tin->SetBranchAddress("Pdc217", &Pdc2[17]);
  Tin->SetBranchAddress("Pdc218", &Pdc2[18]);
  Tin->SetBranchAddress("Pdc219", &Pdc2[19]);
  Tin->SetBranchAddress("Pdc220", &Pdc2[20]);
  Tin->SetBranchAddress("Pdc221", &Pdc2[21]);
  Tin->SetBranchAddress("Pdc222", &Pdc2[22]);
  Tin->SetBranchAddress("Pdc223", &Pdc2[23]);
  Tin->SetBranchAddress("Pdc224", &Pdc2[24]);
  Tin->SetBranchAddress("Pdc225", &Pdc2[25]);
  Tin->SetBranchAddress("Pdc226", &Pdc2[26]);
  Tin->SetBranchAddress("Pdc227", &Pdc2[27]);
  Tin->SetBranchAddress("Pdc228", &Pdc2[28]);
  Tin->SetBranchAddress("Pdc229", &Pdc2[29]);
  Tin->SetBranchAddress("Pdc230", &Pdc2[30]);
  Tin->SetBranchAddress("Pdc231", &Pdc2[31]);

  Tin->SetBranchAddress("Padc0",  &Padc[0]);
  Tin->SetBranchAddress("Padc1",  &Padc[1]);
  Tin->SetBranchAddress("Padc2",  &Padc[2]);
  Tin->SetBranchAddress("Padc3",  &Padc[3]);
  Tin->SetBranchAddress("Padc4",  &Padc[4]);
  Tin->SetBranchAddress("Padc5",  &Padc[5]);
  Tin->SetBranchAddress("Padc6",  &Padc[6]);
  Tin->SetBranchAddress("Padc7",  &Padc[7]);
  Tin->SetBranchAddress("Padc8",  &Padc[8]);
  Tin->SetBranchAddress("Padc9",  &Padc[9]);
  Tin->SetBranchAddress("Padc10", &Padc[10]);
  Tin->SetBranchAddress("Padc11", &Padc[11]);
  Tin->SetBranchAddress("Padc12", &Padc[12]);
  Tin->SetBranchAddress("Padc13", &Padc[13]);
  Tin->SetBranchAddress("Padc14", &Padc[14]);
  Tin->SetBranchAddress("Padc15", &Padc[15]);
  Tin->SetBranchAddress("Padc16", &Padc[16]);
  Tin->SetBranchAddress("Padc17", &Padc[17]);
  Tin->SetBranchAddress("Padc18", &Padc[18]);
  Tin->SetBranchAddress("Padc19", &Padc[19]);
  Tin->SetBranchAddress("Padc20", &Padc[20]);
  Tin->SetBranchAddress("Padc21", &Padc[21]);
  Tin->SetBranchAddress("Padc22", &Padc[22]);
  Tin->SetBranchAddress("Padc23", &Padc[23]);
  Tin->SetBranchAddress("Padc24", &Padc[24]);
  Tin->SetBranchAddress("Padc25", &Padc[25]);
  Tin->SetBranchAddress("Padc26", &Padc[26]);
  Tin->SetBranchAddress("Padc27", &Padc[27]);
  Tin->SetBranchAddress("Padc28", &Padc[28]);
  Tin->SetBranchAddress("Padc29", &Padc[29]);
  Tin->SetBranchAddress("Padc30", &Padc[30]);
  Tin->SetBranchAddress("Padc31", &Padc[31]);

  Tin->SetBranchAddress("S83028", &S83028);
  Tin->SetBranchAddress("S8200", &S8200);
  Tin->SetBranchAddress("Clk0", &Clk0);
  Tin->SetBranchAddress("Clk1", &Clk1);
  Tin->SetBranchAddress("Clk2", &Clk2);
  Tin->SetBranchAddress("Clk3", &Clk3);

  Tin->SetBranchAddress("Pdc38",  &Pdc38);
  Tin->SetBranchAddress("Pdc39",  &Pdc39);
  Tin->SetBranchAddress("Pdc310", &Pdc310);
  Tin->SetBranchAddress("Pdc311", &Pdc311);

  Tin->SetBranchAddress("Qadc9",  &Qadc9);
  Tin->SetBranchAddress("Tdc019", &Tdc019);
  Tin->SetBranchAddress("Pdc313", &Pdc313);
  Tin->SetBranchAddress("Pdc315", &Pdc315);
  Tin->SetBranchAddress("Qadc8",  &Qadc8);
  Tin->SetBranchAddress("Tdc018", &Tdc018);
  Tin->SetBranchAddress("Qadc10", &Qadc10);
  Tin->SetBranchAddress("Tdc020", &Tdc020);

  Tin->SetBranchAddress("Number", &Number);
  Tin->SetBranchAddress("Delt0", &Delt0);

  Tin->SetBranchAddress("Evnb0", &Evnb[0]);
  Tin->SetBranchAddress("Evnb1", &Evnb[1]);
  Tin->SetBranchAddress("Evnb2", &Evnb[2]);
  Tin->SetBranchAddress("Evnb3", &Evnb[3]);
  Tin->SetBranchAddress("Evnb4", &Evnb[4]);
  Tin->SetBranchAddress("Bkhf0", &Bkhf[0]);
  Tin->SetBranchAddress("Bkhf1", &Bkhf[1]);
  Tin->SetBranchAddress("Bkhf2", &Bkhf[2]);
  Tin->SetBranchAddress("Bkhf3", &Bkhf[3]);
  Tin->SetBranchAddress("Bkhf4", &Bkhf[4]);


  int nEvents = Tin->GetEntries();
  cout << "... Processing nEvents = " << nEvents << endl;

  //Get length of run from UNBLINDED TIME
  float runLengthBlind[2] = {0.};
  float runLengthTrue = 0.;
  Tin->GetEvent(nEvents-1);
  runLengthTrue = S83028*scalerCountsToTime;
  runLengthBlind[0] = Clk0*scalerCountsToTime;
  runLengthBlind[1] = Clk1*scalerCountsToTime;
  
  //Histograms to hold UCNMonRate
  int binWidth = 10;
  int nbins = (int)(runLengthTrue+20.)/binWidth;
  t.UCN_Mon_1_Rate = new TH1F("UCN_Mon_1_Rate","UCN Mon 1 Rate",nbins, 0., (float)nbins*binWidth);
  t.UCN_Mon_2_Rate = new TH1F("UCN_Mon_2_Rate","UCN Mon 2 Rate",nbins, 0., (float)nbins*binWidth);
  t.UCN_Mon_3_Rate = new TH1F("UCN_Mon_3_Rate","UCN Mon 3 Rate",nbins, 0., (float)nbins*binWidth);
  t.UCN_Mon_4_Rate = new TH1F("UCN_Mon_4_Rate","UCN Mon 4 Rate",nbins, 0., (float)nbins*binWidth);
  

  // Loop over events
  for (int i=0; i<nEvents; i++) {
    Tin->GetEvent(i);
    Int_t iSis00 = (int) Sis00;

    // Calculate pedestal-subtracted PMT QADC values
    for (int j=0; j<8; j++) {
      pmt[j] = ((double) Qadc[j]) - pedQadc[j];
    }
    

    // Calculate pedestal-subtracted MWPC cathode PADC values
    for (int j=0; j<32; j++) {
      cathodeEast[j] = ((double) Pdc2[j]) - pedPdc2[j];
      cathodeWest[j] = ((double) Padc[j]) - pedPadc[j];
    }

    // Calculate pedestal-subtracted MWPC Anode PADC values
    //Took this out for now. We are comparing against a cut instead...
    //AnodeE = ((double) Pdc30) - pedPdc30;
    //AnodeW = ((double) Pdc34) - pedPdc34;

    // UCN monitor events
    bool UCNMonitorTrigger = false;
    
    float time = S83028*scalerCountsToTime;
    if (iSis00==260) {t.UCN_Mon_1_Rate->Fill(time,1./binWidth); UCNMonitorTrigger = true;}
    else if (iSis00==516) {t.UCN_Mon_2_Rate->Fill(time,1./binWidth); UCNMonitorTrigger = true;}
    else if (iSis00==1028) {t.UCN_Mon_3_Rate->Fill(time,1./binWidth); UCNMonitorTrigger = true;}
    else if (iSis00==2052) {t.UCN_Mon_4_Rate->Fill(time,1./binWidth); UCNMonitorTrigger = true;}
    

    // Events with a muon hit
    bool muonHitEast = false;
    bool muonHitWest = false;
    if ( (((double) Qadc8)  > cutEastBackingVetoQADC) ||
         (((double) Tdc018) > cutEastBackingVetoTDC)  ||
         (((double) Qadc9)  > cutEastTopVetoQADC)     ||
         (((double) Tdc019) > cutEastTopVetoTDC)      ||
         (((double) Pdc313) > cutEastDriftTubeTAC) ) {
      muonHitEast = true;
    }
    if ( (((double) Qadc10) > cutWestBackingVetoQADC) ||
         (((double) Tdc020) > cutWestBackingVetoTDC)  ||
         (((double) Pdc315) > cutWestDriftTubeTAC) ) {
      muonHitWest = true;
    }
    
    t.TaggedBackE = (((double) Qadc8)  > cutEastBackingVetoQADC || ((double) Tdc018) > cutEastBackingVetoTDC)?true:false;
    t.TaggedBackW = (((double) Qadc10)  > cutWestBackingVetoQADC || ((double) Tdc020) > cutEastBackingVetoTDC)?true:false;
    t.TaggedTopE = (((double) Qadc9)  > cutEastTopVetoQADC || ((double) Tdc019) > cutEastTopVetoTDC)?true:false;
    t.TaggedTopW = false;
    t.TaggedDriftE = (((double) Pdc313)  > cutEastDriftTubeTAC)?true:false;
    t.TaggedDriftW = (((double) Pdc315)  > cutWestDriftTubeTAC)?true:false;

    t.EastBackADC = (double) Qadc8;
    t.WestBackADC = (double) Qadc10;
    t.EastBackTDC = (double) Tdc018;
    t.WestBackTDC = (double) Tdc020;
    t.EastDriftVetoADC = (double) Pdc313;
    t.WestDriftVetoADC = (double) Pdc315;
    t.EastTopVetoADC = (double) Qadc9;
    t.EastTopVetoTDC = (double) Tdc019;
    

    // LED trigger events
    bool LEDTrigger = false;
    if ( (iSis00 == 128) || (iSis00 == 129) || (iSis00 == 130) || (iSis00 == 131) || (iSis00 == 163) ) {
      LEDTrigger = true;
    }

    // Bi pulser trigger events
    bool bismuthPulser = false;
    if (iSis00 == 32) bismuthPulser = true;

    // Scintillator events
    bool mwpcHitEast = false;
    bool mwpcHitWest = false;
    bool scintillatorHitEast = false;
    bool scintillatorHitWest = false;
    bool scintillatorHitBoth = false;
    bool coincidenceEast = false;
    bool coincidenceWest = false;
    bool scintillatorHitFirstEast = false;
    bool scintillatorHitFirstWest = false;
    bool scintillatorHitBothBad = false;
    bool triggerEast = false;
    bool triggerWest = false;

    if ( ((double) Pdc30)  > cutEastAnode) {mwpcHitEast = true; t.PassedAnoE=true;}
    if ( ((double) Pdc34)  > cutWestAnode) {mwpcHitWest = true; t.PassedAnoW=true;}

    double timeEastTwoFold = ((double) Tdc016)*tdcChannelToTime;
    double timeWestTwoFold = ((double) Tdc017)*tdcChannelToTime;
    if (timeEastTwoFold > 0.*tdcChannelToTime) scintillatorHitEast = true;
    if (timeWestTwoFold > 0.*tdcChannelToTime) scintillatorHitWest = true;
    if (scintillatorHitEast && scintillatorHitWest) {
      scintillatorHitBoth = true;
      if ( (timeEastTwoFold > cutEastTwoFold) && (timeWestTwoFold < cutWestTwoFold) ) {
        scintillatorHitFirstEast = true;
      }
      if ( (timeEastTwoFold < cutEastTwoFold) && (timeWestTwoFold > cutWestTwoFold) ) {
        scintillatorHitFirstWest = true;
      }
      if ( (timeEastTwoFold > cutEastTwoFold) && (timeWestTwoFold > cutWestTwoFold) ) {
        scintillatorHitBothBad = true;
      }
      if ( (timeEastTwoFold < cutEastTwoFold) && (timeWestTwoFold < cutWestTwoFold) ) {
        scintillatorHitBothBad = true;
      }
    }

    if (mwpcHitEast && scintillatorHitEast) coincidenceEast = true;
    if (mwpcHitWest && scintillatorHitWest) coincidenceWest = true;

    // Event PID logic
    if (UCNMonitorTrigger) PID = 5;
    else if (LEDTrigger) PID = 3;
    else if (muonHitEast || muonHitWest) PID = 2;
    else if (bismuthPulser) PID = 4;
    else if ( (scintillatorHitEast && !mwpcHitEast && !scintillatorHitWest && !mwpcHitWest) ||
              (!scintillatorHitEast && !mwpcHitEast && scintillatorHitWest && !mwpcHitWest) ) PID = 0;
    else if ( (coincidenceEast && !scintillatorHitWest && !mwpcHitWest) ||
              (!scintillatorHitEast && !mwpcHitEast && coincidenceWest) ||
              (coincidenceEast && coincidenceWest && !scintillatorHitBothBad) ||
              (coincidenceEast && !scintillatorHitWest && mwpcHitWest) ||
              (!scintillatorHitEast && mwpcHitEast && coincidenceWest) ) PID = 1;
    else PID = 6;

    type = -1;
    side = -1;
    if (PID == 1) {
      if (coincidenceEast && !scintillatorHitWest && !mwpcHitWest) {
        type = 0;
        side = 0;
      }
      if (!scintillatorHitEast && !mwpcHitEast && coincidenceWest) {
        type = 0;
        side = 1;
      }
      if (coincidenceEast && coincidenceWest && !scintillatorHitBothBad) {
        type = 1;
        if (scintillatorHitFirstEast) side = 0;
        if (scintillatorHitFirstWest) side = 1;
      }
      if (coincidenceEast && !scintillatorHitWest && mwpcHitWest) {
        type = 2;
        side = 0;
      }
      if (!scintillatorHitEast && mwpcHitEast && coincidenceWest) {
        type = 2;
        side = 1;
      }
    }

    

    
    //////////////////////////////////////////////////////////////////////////////////
    /*  Swank's addition to the UK PA.  (2 of 2)
	this seems like a good spot since its around the position calculation. 
    */

    int xeRC,yeRC,xwRC,ywRC;
    WireChamberResponse * WCR = new WireChamberResponse();

    //changing the length 32 double array to length 16  float array.  using variables defined in WCR. 
    for(int j = 0; j<16; j++)
      {
	WCR->cathex[j]=(float)cathodeEast[16+j];
	WCR->cathey[j]=(float)cathodeEast[j];
	WCR->cathwx[j]=(float)cathodeWest[16+j];
	WCR->cathwy[j]=(float)cathodeWest[j];
      } 
    
    xeRC=WCR->ResponseType(WCR->cathex);   //response class x co-ordinate, East. 
    yeRC=WCR->ResponseType(WCR->cathey);   //response class y co-ordinate, East. 
    xwRC=WCR->ResponseType(WCR->cathwx);   //response class x co-ordinate, West. 
    ywRC=WCR->ResponseType(WCR->cathwy);   //response class y co-ordinate, West.
    /*
      End of swank's addtion (2 of 2)
    */
    ////////////////////////////////////////////////////////////////////////////////////
    
    // Calculate MWPC positions for electron events
    xE = 0.;
    yE = 0.;
    xW = 0.;
    yW = 0.;
    posError = 0.;

    double xMWPCEast = 0.;
    double yMWPCEast = 0.;
    double xMWPCWest = 0.;
    double yMWPCWest = 0.;
    double xMWPCEastSum = 0.;
    double yMWPCEastSum = 0.;
    double xMWPCWestSum = 0.;
    double yMWPCWestSum = 0.;
    double xEmax = 0., yEmax = 0., xWmax = 0., yWmax = 0.; //max adc on wire
    int xEmaxWire=0, yEmaxWire =0, xWmaxWire=0, yWmaxWire=0;  // max wire number
    int xEmult = 0, yEmult = 0, xWmult = 0, yWmult = 0; //Num of wires over threshold

    if (PID==1) {
      for (int j=0; j<16; j++) {
      
	if (cathodeEast[j+16] > 100.) {
	  xMWPCEast += cathodeEast[j+16]*posPdc2[j+16];
	  xMWPCEastSum += cathodeEast[j+16];
	  t.Cathodes_Ex[j] = cathodeEast[j+16];
	  xEmult++;
	  if (cathodeEast[j+16]>xEmax) {
	    xEmax = cathodeEast[j+16];
	    xEmaxWire = j; 
	  }
	}
	if (cathodeEast[j] > 100.) {
	  yMWPCEast += cathodeEast[j]*posPdc2[j];
	  yMWPCEastSum += cathodeEast[j];
	  t.Cathodes_Ey[j] = cathodeEast[j];
	  yEmult++;
	  if (cathodeEast[j]>yEmax) {
	    yEmax = cathodeEast[j];
	    yEmaxWire = j; 
	  }
	}
	if (cathodeWest[j+16] > 100.) {
	  xMWPCWest += cathodeWest[j+16]*posPadc[j+16];
	  xMWPCWestSum += cathodeWest[j+16];
	  t.Cathodes_Wx[j] = cathodeWest[j+16];
	  xWmult++;
	  if (cathodeWest[j+16]>xWmax) {
	    xWmax = cathodeWest[j+16];
	    xWmaxWire = j; 
	  }
	}
	if (cathodeWest[j] > 100.) {
	  yMWPCWest += cathodeWest[j]*posPadc[j];
	  yMWPCWestSum += cathodeWest[j];
	  t.Cathodes_Wy[j] = cathodeEast[j];
	  yWmult++;
	  if (cathodeWest[j]>yWmax) {
	    yWmax = cathodeWest[j];
	    yWmaxWire = j; 
	  }
	}
      }
       
      if (xMWPCEastSum > 0.)
	xMWPCEast = xMWPCEast / xMWPCEastSum;
      if (yMWPCEastSum > 0.)
	yMWPCEast = yMWPCEast / yMWPCEastSum;
      if (xMWPCWestSum > 0.)
	xMWPCWest = xMWPCWest / xMWPCWestSum;
      if (yMWPCWestSum > 0.)
	yMWPCWest = yMWPCWest / yMWPCWestSum;
      
      if (mwpcHitEast && xMWPCEastSum > 0.)
	xE = xMWPCEast * positionProjection;
      if (mwpcHitEast && yMWPCEastSum > 0.)
	yE = yMWPCEast * positionProjection;
      if (mwpcHitWest && xMWPCWestSum > 0.)
	xW = xMWPCWest * positionProjection;
      if (mwpcHitWest && yMWPCWestSum > 0.)
	yW = yMWPCWest * positionProjection;
      
    }

    // Pass Everything to output tree
    t.TriggerNum = (int) Number;
    t.EvtN = i;
    t.Sis00 = iSis00;
    t.DeltaT = ((double)Delt0)*scalerCountsToTime;
    t.Tof = (double) S8200;
    t.TimeE = Clk0*scalerCountsToTime;
    t.TimeW = Clk1*scalerCountsToTime;
    t.Time = S83028*scalerCountsToTime;
    t.TDCE = (double) Tdc016;
    t.TDCW = (double) Tdc017;
    t.TDCE1 = (double) Tdc00;
    t.TDCE2 = (double) Tdc01;
    t.TDCE3 = (double) Tdc02;
    t.TDCE4 = (double) Tdc03;
    t.TDCW1 = (double) Tdc08;
    t.TDCW2 = (double) Tdc09;
    t.TDCW3 = (double) Tdc010;
    t.TDCW4 = (double) Tdc011;
    
    //Wirechambers
    t.xE.center = xE;
    t.xE.width = 0.;
    t.xE.cathSum = xMWPCEastSum;
    t.xE.maxValue = xEmax;
    t.xE.maxWire = xEmaxWire;
    t.xE.mult = xEmult;
    t.xE.nClipped = 0;
    t.xE.err = 0.;
    t.xE.rawCenter = 0.;
    t.xE.height = 0.;
    
    t.yE.center = yE;
    t.yE.width = 0.;
    t.yE.cathSum = yMWPCEastSum;
    t.yE.maxValue = yEmax;
    t.yE.maxWire = yEmaxWire;
    t.yE.mult = yEmult;
    t.yE.nClipped = 0;
    t.yE.err = 0.;
    t.yE.rawCenter = 0.;
    t.yE.height = 0.;
    
    t.xW.center = xW;
    t.xW.width = 0.;
    t.xW.cathSum = xMWPCWestSum;
    t.xW.maxValue = xWmax;
    t.xW.maxWire = xWmaxWire;
    t.xW.mult = xWmult;
    t.xW.nClipped = 0;
    t.xW.err = 0.;
    t.xW.rawCenter = 0.;
    t.xW.height = 0.;
    
    t.yW.center = yW;
    t.yW.width = 0.;
    t.yW.cathSum = yMWPCWestSum;
    t.yW.maxValue = yWmax;
    t.yW.maxWire = yWmaxWire;
    t.yW.mult = yWmult;
    t.yW.nClipped = 0;
    t.yW.err = 0.;
    t.yW.rawCenter = 0.;
    t.yW.height = 0.;
    
    t.ScintE.q1 = pmt[0];
    t.ScintE.q2 = pmt[1];
    t.ScintE.q3 = pmt[2];
    t.ScintE.q4 = pmt[3]; 
    t.ScintE.e1=t.ScintE.de1=t.ScintE.e2=t.ScintE.de2=t.ScintE.e3=t.ScintE.de3=t.ScintE.e4=t.ScintE.de4=0.;
    t.ScintE.energy=t.ScintE.denergy=0.;
    t.ScintE.nPE1=t.ScintE.nPE2=t.ScintE.nPE3=t.ScintE.nPE4=0.;
    
    t.ScintW.q1 = pmt[4];
    t.ScintW.q2 = pmt[5];
    t.ScintW.q3 = pmt[6];
    t.ScintW.q4 = pmt[7]; 
    t.ScintW.e1=t.ScintW.de1=t.ScintW.e2=t.ScintW.de2=t.ScintW.e3=t.ScintW.de3=t.ScintW.e4=t.ScintW.de4=0.;
    t.ScintW.energy=t.ScintW.denergy=0.;
    t.ScintW.nPE1=t.ScintW.nPE2=t.ScintW.nPE3=t.ScintW.nPE4=0.;
    
    t.EvisE = t.EvisW = 0.;
    
    t.CathSumE =  t.xE.cathSum+t.yE.cathSum;
    t.CathSumW =  t.xW.cathSum+t.yW.cathSum;
    
    t.CathMaxE = (t.xE.maxValue>t.yE.maxValue)?t.yE.maxValue:t.xE.maxValue;
    t.CathMaxW = (t.xW.maxValue>t.yW.maxValue)?t.yW.maxValue:t.xW.maxValue;
    
    t.EMWPC_E = t.EMWPC_W = 0.;
    
    t.AnodeE = (double) Pdc30;
    t.AnodeW = (double) Pdc34;
    
    t.PassedCathE = t.PassedCathW = PID==1?true:false; //temporary holder for this
    
    t.EvnbGood = t.BkhfGood = true;
    for (Int_t i = 0; i<5; i++) {
      if ((int)Evnb[i]-t.TriggerNum) t.EvnbGood = false;
      if ((int)Bkhf[i]!=17) t.BkhfGood = false;
    }
    
    t.xeRC = xeRC;
    t.yeRC = yeRC;
    t.xwRC = xwRC;
    t.ywRC = ywRC;
    
    t.PID = PID;
    t.Type = type;
    t.Side = side;
    t.ProbIII = 0.;
    t.Erecon = 0.;


      /*timeE_BB = Clk2*scalerCountsToTime;
      timeW_BB = Clk3*scalerCountsToTime;
      UBtime = S83028*scalerCountsToTime;
      UBtime_BB = S8200*scalerCountsToTime;
      twoFoldE = Tdc016;
      twoFoldW = Tdc017;*/
  
    t.fillOutputTree();
    
  }
  
  fileIn->Close();

  //Now I want to create and store a few pertinent values in a file for later...
  char tempFile[200];
  sprintf(tempFile,"%s/runInfo_%s.dat",getenv("RUN_INFO_FILES"),argv[1]);
  ofstream runInfo(tempFile);
  std::cout << "Writing Info to " << tempFile << std::endl;

  runInfo << "RunLengthEast\t" << std::setprecision(9) << runLengthBlind[0] << std::endl;
  runInfo << "RunLengthWest\t" << std::setprecision(9) << runLengthBlind[1] << std::endl;
  runInfo << "RunLengthTrue\t" << std::setprecision(9) << runLengthTrue << std::endl;
  runInfo << "UCNMon4Integral\t" << std::setprecision(9) << t.UCN_Mon_4_Rate->Integral("width");

  runInfo.close();
  // Write output ntuple
  t.writeOutputFile();
  //fileOut->Close();

  return 0;
}
int main(int argc, char *argv[])
{

  if ( argc<2 || argc>3 ) {
    std::cout << "USAGE: ./replay_pass3.exe [run] [applyEndpointGain = false]\n\n";
    exit(0);
  }
  
  cout.setf(ios::fixed, ios::floatfield);
  cout.precision(12);
  
  int runNumber = atoi(argv[1]);
  bool applyEndpointGain = false;
  if ( argc==3 && ( TString(argv[2])==TString("true") || atoi(argv[2])==1 ) ) applyEndpointGain = true; 

  
  int nPMT = 8;
  int nParams = 3; //takes a quadratic 

  // Run number integer
  cout << "Run " << runNumber << " ..." << endl;

  char tempOut[500];
  sprintf(tempOut, "%s/replay_pass3_%s.root",getenv("REPLAY_PASS3"), argv[1]);
  //sprintf(tempOut, "replay_pass3_%s.root", argv[1]);

  //Check if the file is good already and quit if it is so that we can 
  // only replay the files that are bad...

  if ( OnlyReplayBadFiles ) {
     
    if ( checkIfReplayFileIsGood(std::string(tempOut)) == 1 ) return 1;
  
    else {
      std::ofstream badRuns("badRuns.txt", std::fstream::app);
      badRuns << argv[1] << "\n";
      badRuns.close();
    }
  }

  // Reading in pedestals file to get cathode pedestals
  // Read pedestals file
  char tempFilePed[500];
  int iRun;
  sprintf(tempFilePed, "%s/pedestals_%s.dat", getenv("PEDESTALS"), argv[1]);
  std::cout << "... Reading: " << tempFilePed << std::endl;

  std::ifstream filePed(tempFilePed);
  for (int i=0; i<8; i++) {
    filePed >> iRun >> pedQadc[i];   
  }
  for (int i=0; i<32; i++) {
    filePed >> iRun >> pedPdc2[i];
  }
  for (int i=0; i<32; i++) {
    filePed >> iRun >> pedPadc[i];
  }

  
  filePed >> iRun >> pedPdc30;
  filePed >> iRun >> pedPdc34;
  


  cout << "... Applying Calibration ..." << endl;

  unsigned int calibrationPeriod = getSrcRunPeriod(runNumber);
  
  LinearityCurve linearityCurve(calibrationPeriod,false); //Get the linearity curve  
  EreconParameterization eRecon(runNumber); //Load the simulated relationship between EQ and Etrue
  WirechamberCal mwpcCal(runNumber);        //Load the Wirechamber Calibration

  std::vector <Double_t> epGain(8,1.); // Loading the endpoint gain factors if they are to be used
  if ( applyEndpointGain ) epGain = loadEndpointGain(runNumber);
  
  std::vector <Int_t> pmtQuality = getEreconPMTQuality(runNumber); //Read in PMT quality file
  std::vector <Double_t> alpha = GetAlphaValues(calibrationPeriod); //Get values for nPE/keV...
    
  PositionMap posmap(5.0,50.); //Reading Scintillator position maps
  posmap.readPositionMap( getXeRunPeriod(runNumber), "endpoint" );

  MWPCPositionMap anodeMap(5., 50.);    // Reading Anode position maps
  anodeMap.readMWPCPositionMap( getXeRunPeriodForMWPCmap(runNumber) ,250.,300.); // Using 250-300 keV because that's the most probable range

  
  DataTree *t = new DataTree(); // DataTree structure for input pass2 and output pass3
  t->makeOutputTree(std::string(tempOut),"pass3");  // Open output ntuple

  // Input ntuple
  char tempIn[500];
  sprintf(tempIn, "%s/replay_pass2_%s.root", getenv("REPLAY_PASS2"),argv[1]);
  t->setupInputTree(std::string(tempIn),"pass2");
 
  int nEvents = t->getEntries();
  cout << "... Processing nEvents = " << nEvents << endl;

  vector < vector <Int_t> > gridPoint;
  vector < Double_t > eta;
  vector < Double_t > old_eta;
  vector < Double_t > gaus_eta;


  // Loop over events
  for (int i=0; i<nEvents; i++) {
    t->getEvent(i);

    if ( i%10000==0 ) std::cout << i << std::endl;

    // Only process event if it's an electron
    
    if ( t->PID==1 || t->PID==6 ) { //PID==6 includes the APD events as they don't have coincidence on one side...

      std::vector <double> posex(3,0.);
      std::vector <double> poswx(3,0.);
      std::vector <double> posey(3,0.);
      std::vector <double> poswy(3,0.);

      MWPCCathodeHandler cathResp(t->Cathodes_Ex,t->Cathodes_Ey,t->Cathodes_Wx,t->Cathodes_Wy,&pedPdc2[16],&pedPdc2[0],&pedPadc[16],&pedPadc[0]);
 
  
      //First do the normal way... weighted average of good events, gaus fit of clipped
      cathResp.findAllPositions(true,false);
      
      posex = cathResp.getPosEX();
      posey = cathResp.getPosEY();
      poswx = cathResp.getPosWX();
      poswy = cathResp.getPosWY();

      t->xE.center = posex[0] * positionProjection;
      t->yE.center = posey[0] * positionProjection;
      t->xW.center = poswx[0] * positionProjection;
      t->yW.center = poswy[0] * positionProjection;

      t->xE.width = posex[1] * positionProjection;
      t->yE.width = posey[1] * positionProjection;
      t->xW.width = poswx[1] * positionProjection;
      t->yW.width = poswy[1] * positionProjection;
      
      t->xE.height = posex[2];
      t->yE.height = posey[2];
      t->xW.height = poswx[2];
      t->yW.height = poswy[2];

      t->xE.mult = cathResp.getMultEX();
      t->yE.mult = cathResp.getMultEY();
      t->xW.mult = cathResp.getMultWX();
      t->yW.mult = cathResp.getMultWY();

      t->xE.nClipped = cathResp.getnClippedEX();
      t->yE.nClipped = cathResp.getnClippedEY();
      t->xW.nClipped = cathResp.getnClippedWX();
      t->yW.nClipped = cathResp.getnClippedWY();

      t->xE.maxWire = cathResp.getMaxWireEX();
      t->yE.maxWire = cathResp.getMaxWireEY();
      t->xW.maxWire = cathResp.getMaxWireWX();
      t->yW.maxWire = cathResp.getMaxWireWY();

      t->xE.maxValue = cathResp.getMaxSignalEX();
      t->yE.maxValue = cathResp.getMaxSignalEY();
      t->xW.maxValue = cathResp.getMaxSignalWX();
      t->yW.maxValue = cathResp.getMaxSignalWY();

      t->xE.cathSum = cathResp.getCathSumEX();
      t->yE.cathSum = cathResp.getCathSumEY();
      t->xW.cathSum = cathResp.getCathSumWX();
      t->yW.cathSum = cathResp.getCathSumWY();

      t->CathSumE = t->xE.cathSum + t->yE.cathSum;
      t->CathSumW = t->xW.cathSum + t->yW.cathSum;

      t->CathMaxE = t->xE.maxValue + t->yE.maxValue;
      t->CathMaxW = t->xW.maxValue + t->yW.maxValue;
	    
      t->xE.rawCenter = cathResp.getWirePosEX(t->xE.maxWire);
      t->yE.rawCenter = cathResp.getWirePosEY(t->yE.maxWire);
      t->xW.rawCenter = cathResp.getWirePosWX(t->xW.maxWire);
      t->yW.rawCenter = cathResp.getWirePosWY(t->yW.maxWire);

      
      //Now do all gaussian fits... 
      //cathResp.loadGainFactors(runNumber);

      cathResp.findAllPositions(true,true);

      posex = cathResp.getPosEX();
      posey = cathResp.getPosEY();
      poswx = cathResp.getPosWX();
      poswy = cathResp.getPosWY();

      t->gaus_xE.center = posex[0] * positionProjection;
      t->gaus_yE.center = posey[0] * positionProjection;
      t->gaus_xW.center = poswx[0] * positionProjection;
      t->gaus_yW.center = poswy[0] * positionProjection;

      t->gaus_xE.width = posex[1] * positionProjection;
      t->gaus_yE.width = posey[1] * positionProjection;
      t->gaus_xW.width = poswx[1] * positionProjection;
      t->gaus_yW.width = poswy[1] * positionProjection;
      
      t->gaus_xE.height = posex[2];
      t->gaus_yE.height = posey[2];
      t->gaus_xW.height = poswx[2];
      t->gaus_yW.height = poswy[2];

      t->gaus_xE.mult = cathResp.getMultEX();
      t->gaus_yE.mult = cathResp.getMultEY();
      t->gaus_xW.mult = cathResp.getMultWX();
      t->gaus_yW.mult = cathResp.getMultWY();

      t->gaus_xE.nClipped = cathResp.getnClippedEX();
      t->gaus_yE.nClipped = cathResp.getnClippedEY();
      t->gaus_xW.nClipped = cathResp.getnClippedWX();
      t->gaus_yW.nClipped = cathResp.getnClippedWY();

      t->gaus_xE.maxWire = cathResp.getMaxWireEX();
      t->gaus_yE.maxWire = cathResp.getMaxWireEY();
      t->gaus_xW.maxWire = cathResp.getMaxWireWX();
      t->gaus_yW.maxWire = cathResp.getMaxWireWY();
      
      t->gaus_xE.maxValue = cathResp.getMaxSignalEX();
      t->gaus_yE.maxValue = cathResp.getMaxSignalEY();
      t->gaus_xW.maxValue = cathResp.getMaxSignalWX();
      t->gaus_yW.maxValue = cathResp.getMaxSignalWY();

      t->gaus_xE.cathSum = cathResp.getCathSumEX();
      t->gaus_yE.cathSum = cathResp.getCathSumEY();
      t->gaus_xW.cathSum = cathResp.getCathSumWX();
      t->gaus_yW.cathSum = cathResp.getCathSumWY();

      t->gaus_xE.rawCenter = cathResp.getWirePosEX(t->xE.maxWire);
      t->gaus_yE.rawCenter = cathResp.getWirePosEY(t->yE.maxWire);
      t->gaus_xW.rawCenter = cathResp.getWirePosWX(t->xW.maxWire);
      t->gaus_yW.rawCenter = cathResp.getWirePosWY(t->yW.maxWire);


      
      // Now for all weighted averages...
      cathResp.purgeGainFactors();
      cathResp.findAllPositions(false,false);

      posex = cathResp.getPosEX();
      posey = cathResp.getPosEY();
      poswx = cathResp.getPosWX();
      poswy = cathResp.getPosWY();

      t->old_xE.center = posex[0] * positionProjection;
      t->old_yE.center = posey[0] * positionProjection;
      t->old_xW.center = poswx[0] * positionProjection;
      t->old_yW.center = poswy[0] * positionProjection;

      t->old_xE.width = posex[1] * positionProjection;
      t->old_yE.width = posey[1] * positionProjection;
      t->old_xW.width = poswx[1] * positionProjection;
      t->old_yW.width = poswy[1] * positionProjection;
      
      t->old_xE.height = posex[2];
      t->old_yE.height = posey[2];
      t->old_xW.height = poswx[2];
      t->old_yW.height = poswy[2];

      t->old_xE.mult = cathResp.getMultEX();
      t->old_yE.mult = cathResp.getMultEY();
      t->old_xW.mult = cathResp.getMultWX();
      t->old_yW.mult = cathResp.getMultWY();

      t->old_xE.nClipped = cathResp.getnClippedEX();
      t->old_yE.nClipped = cathResp.getnClippedEY();
      t->old_xW.nClipped = cathResp.getnClippedWX();
      t->old_yW.nClipped = cathResp.getnClippedWY();

      t->old_xE.maxWire = cathResp.getMaxWireEX();
      t->old_yE.maxWire = cathResp.getMaxWireEY();
      t->old_xW.maxWire = cathResp.getMaxWireWX();
      t->old_yW.maxWire = cathResp.getMaxWireWY();

      t->old_xE.maxValue = cathResp.getMaxSignalEX();
      t->old_yE.maxValue = cathResp.getMaxSignalEY();
      t->old_xW.maxValue = cathResp.getMaxSignalWX();
      t->old_yW.maxValue = cathResp.getMaxSignalWY();

      t->old_xE.cathSum = cathResp.getCathSumEX();
      t->old_yE.cathSum = cathResp.getCathSumEY();
      t->old_xW.cathSum = cathResp.getCathSumWX();
      t->old_yW.cathSum = cathResp.getCathSumWY();

      t->old_xE.rawCenter = cathResp.getWirePosEX(t->xE.maxWire);
      t->old_yE.rawCenter = cathResp.getWirePosEY(t->yE.maxWire);
      t->old_xW.rawCenter = cathResp.getWirePosWX(t->xW.maxWire);
      t->old_yW.rawCenter = cathResp.getWirePosWY(t->yW.maxWire);

      
      /////////////////////////////////////////////////////////////
      /////// Now do the energy reconstruction
      /*std::cout << "Event " << i << std::endl;    
      std::cout << "Optimal: " << t->xE.center << "\t" << t->yE.center << "\t" << t->xW.center << "\t" << t->yW.center << "\n"
		<< "Old: " << t->old_xE.center << "\t" << t->old_yE.center << "\t" << t->old_xW.center << "\t" << t->old_yW.center << "\n"
		<< "Gaus: " << t->gaus_xE.center << "\t" << t->gaus_yE.center << "\t" << t->gaus_xW.center << "\t" << t->gaus_yW.center << "\n\n" ;*/

      eta = posmap.getInterpolatedEta(t->xE.center, t->yE.center, t->xW.center, t->yW.center);
      old_eta = posmap.getInterpolatedEta(t->old_xE.center, t->old_yE.center, t->old_xW.center, t->old_yW.center);
      gaus_eta = posmap.getInterpolatedEta(t->gaus_xE.center, t->gaus_yE.center, t->gaus_xW.center, t->gaus_yW.center);
      
      //First calculate old position reconstruction old_Erecon
      t->ScintE.e1 = linearityCurve.applyLinCurve(0,t->ScintE.q1) * epGain[0];
      t->ScintE.e2 = linearityCurve.applyLinCurve(1,t->ScintE.q2) * epGain[1];
      t->ScintE.e3 = linearityCurve.applyLinCurve(2,t->ScintE.q3) * epGain[2];
      t->ScintE.e4 = linearityCurve.applyLinCurve(3,t->ScintE.q4) * epGain[3];
      
      t->ScintE.e1 = ( old_eta[0]>0. && t->ScintE.e1>0. ) ? t->ScintE.e1 / old_eta[0] : 0.;
      t->ScintE.e2 = ( old_eta[1]>0. && t->ScintE.e2>0. ) ? t->ScintE.e2 / old_eta[1] : 0.;
      t->ScintE.e3 = ( old_eta[2]>0. && t->ScintE.e3>0. ) ? t->ScintE.e3 / old_eta[2] : 0.;
      t->ScintE.e4 = ( old_eta[3]>0. && t->ScintE.e4>0. ) ? t->ScintE.e4 / old_eta[3] : 0.;
      
      t->ScintE.nPE1 = old_eta[0] > 0. ? t->ScintE.e1 * old_eta[0] * alpha[0] : 0.;
      t->ScintE.nPE2 = old_eta[1] > 0. ? t->ScintE.e2 * old_eta[1] * alpha[1] : 0.;
      t->ScintE.nPE3 = old_eta[2] > 0. ? t->ScintE.e3 * old_eta[2] * alpha[2] : 0.;
      t->ScintE.nPE4 = old_eta[3] > 0. ? t->ScintE.e4 * old_eta[3] * alpha[3] : 0.;
      
      t->ScintE.de1 = t->ScintE.nPE1 > 0. ? t->ScintE.e1/sqrt(t->ScintE.nPE1) : 0.;
      t->ScintE.de2 = t->ScintE.nPE2 > 0. ? t->ScintE.e2/sqrt(t->ScintE.nPE2) : 0.;
      t->ScintE.de3 = t->ScintE.nPE3 > 0. ? t->ScintE.e3/sqrt(t->ScintE.nPE3) : 0.;
      t->ScintE.de4 = t->ScintE.nPE4 > 0. ? t->ScintE.e4/sqrt(t->ScintE.nPE4) : 0.;
      
      
      t->ScintW.e1 = linearityCurve.applyLinCurve(4,t->ScintW.q1) * epGain[4];
      t->ScintW.e2 = linearityCurve.applyLinCurve(5,t->ScintW.q2) * epGain[5];
      t->ScintW.e3 = linearityCurve.applyLinCurve(6,t->ScintW.q3) * epGain[6];
      t->ScintW.e4 = linearityCurve.applyLinCurve(7,t->ScintW.q4) * epGain[7];
      
      t->ScintW.e1 = ( old_eta[4]>0. && t->ScintW.e1>0. ) ? t->ScintW.e1 / old_eta[4] : 0.;
      t->ScintW.e2 = ( old_eta[5]>0. && t->ScintW.e2>0. ) ? t->ScintW.e2 / old_eta[5] : 0.;
      t->ScintW.e3 = ( old_eta[6]>0. && t->ScintW.e3>0. ) ? t->ScintW.e3 / old_eta[6] : 0.;
      t->ScintW.e4 = ( old_eta[7]>0. && t->ScintW.e4>0. ) ? t->ScintW.e4 / old_eta[7] : 0.;
      
      t->ScintW.nPE1 = old_eta[4] > 0. ? t->ScintW.e1 * old_eta[4] * alpha[4] : 0.;
      t->ScintW.nPE2 = old_eta[5] > 0. ? t->ScintW.e2 * old_eta[5] * alpha[5] : 0.;
      t->ScintW.nPE3 = old_eta[6] > 0. ? t->ScintW.e3 * old_eta[6] * alpha[6] : 0.;
      t->ScintW.nPE4 = old_eta[7] > 0. ? t->ScintW.e4 * old_eta[7] * alpha[7] : 0.;
      
      t->ScintW.de1 = t->ScintW.nPE1 > 0. ? t->ScintW.e1/sqrt(t->ScintW.nPE1) : 0.;
      t->ScintW.de2 = t->ScintW.nPE2 > 0. ? t->ScintW.e2/sqrt(t->ScintW.nPE2) : 0.;
      t->ScintW.de3 = t->ScintW.nPE3 > 0. ? t->ScintW.e3/sqrt(t->ScintW.nPE3) : 0.;
      t->ScintW.de4 = t->ScintW.nPE4 > 0. ? t->ScintW.e4/sqrt(t->ScintW.nPE4) : 0.;
      
      //std::cout << "Made it here" << std::endl;
      
      
      //Calculate the weighted energy on a side
      
      //EAST
      Double_t numer = ( (pmtQuality[0] && t->ScintE.nPE1>0. ? t->ScintE.nPE1 : 0.) +
			 (pmtQuality[1] && t->ScintE.nPE1>0. ? t->ScintE.nPE2 : 0.) + 
			 (pmtQuality[2] && t->ScintE.nPE1>0. ? t->ScintE.nPE3 : 0.) + 
			 (pmtQuality[3] && t->ScintE.nPE1>0. ? t->ScintE.nPE4 : 0.) );
      
      Double_t denom  = ( (pmtQuality[0] && t->ScintE.nPE1>0. ? alpha[0] * old_eta[0] : 0.) +
			  (pmtQuality[1] && t->ScintE.nPE2>0. ? alpha[1] * old_eta[1] : 0.) +
			  (pmtQuality[2] && t->ScintE.nPE3>0. ? alpha[2] * old_eta[2] : 0.) + 
			  (pmtQuality[3] && t->ScintE.nPE4>0. ? alpha[3] * old_eta[3] : 0.) ); 
      
      t->ScintE.energy = t->EvisE = (denom!=0. ? numer/denom : 0.);
      t->ScintE.denergy = (denom!=0. ? sqrt(t->ScintE.energy/denom) : 0.);
      
      //WEST
      numer = denom = 0.;
      
      numer = ( (pmtQuality[4] && t->ScintW.nPE1>0. ? t->ScintW.nPE1 : 0.) +
		(pmtQuality[5] && t->ScintW.nPE1>0. ? t->ScintW.nPE2 : 0.) + 
		(pmtQuality[6] && t->ScintW.nPE1>0. ? t->ScintW.nPE3 : 0.) + 
		(pmtQuality[7] && t->ScintW.nPE1>0. ? t->ScintW.nPE4 : 0.) );
      
      denom  = ( (pmtQuality[4] && t->ScintW.nPE1>0. ? alpha[4] * old_eta[4] : 0.) +
		 (pmtQuality[5] && t->ScintW.nPE2>0. ? alpha[5] * old_eta[5] : 0.) +
		 (pmtQuality[6] && t->ScintW.nPE3>0. ? alpha[6] * old_eta[6] : 0.) + 
		 (pmtQuality[7] && t->ScintW.nPE4>0. ? alpha[7] * old_eta[7] : 0.) ); 
      
      
      t->ScintW.energy = t->EvisW = (denom!=0. ? numer/denom : 0.);
      t->ScintW.denergy = (denom!=0. ? sqrt(t->ScintW.energy/denom) : 0.);
      
      
      // Determine the reconstructed energy
      
      int typeIndex = t->Type==0 ? 0:(t->Type==1 ? 1:2); //for retrieving the parameters from EQ2Etrue
      
      double totalEvis=0.;
      
      if (t->Side==0) {
	totalEvis = t->Type==1 ? (t->EvisE+t->EvisW):t->EvisE;
	if (t->EvisE>0. && totalEvis>0.) {
	  t->old_Erecon = eRecon.getErecon(0,typeIndex,totalEvis);
	}
	else t->old_Erecon=-1.;
      }
      if (t->Side==1) {
	totalEvis = t->Type==1 ? (t->EvisE+t->EvisW):t->EvisW;
	if (t->EvisW>0. && totalEvis>0.) {
	  t->old_Erecon = eRecon.getErecon(1,typeIndex,totalEvis);
	}
	else t->old_Erecon=-1.;
      }
    

      ////////////////////////////////////////////////////////////////////
      
      //First calculate old position reconstruction gaus_Erecon
      t->ScintE.e1 = linearityCurve.applyLinCurve(0,t->ScintE.q1) * epGain[0];
      t->ScintE.e2 = linearityCurve.applyLinCurve(1,t->ScintE.q2) * epGain[1];
      t->ScintE.e3 = linearityCurve.applyLinCurve(2,t->ScintE.q3) * epGain[2];
      t->ScintE.e4 = linearityCurve.applyLinCurve(3,t->ScintE.q4) * epGain[3];
      
      t->ScintE.e1 = ( gaus_eta[0]>0. && t->ScintE.e1>0. ) ? t->ScintE.e1 / gaus_eta[0] : 0.;
      t->ScintE.e2 = ( gaus_eta[1]>0. && t->ScintE.e2>0. ) ? t->ScintE.e2 / gaus_eta[1] : 0.;
      t->ScintE.e3 = ( gaus_eta[2]>0. && t->ScintE.e3>0. ) ? t->ScintE.e3 / gaus_eta[2] : 0.;
      t->ScintE.e4 = ( gaus_eta[3]>0. && t->ScintE.e4>0. ) ? t->ScintE.e4 / gaus_eta[3] : 0.;
      
      t->ScintE.nPE1 = gaus_eta[0] > 0. ? t->ScintE.e1 * gaus_eta[0] * alpha[0] : 0.;
      t->ScintE.nPE2 = gaus_eta[1] > 0. ? t->ScintE.e2 * gaus_eta[1] * alpha[1] : 0.;
      t->ScintE.nPE3 = gaus_eta[2] > 0. ? t->ScintE.e3 * gaus_eta[2] * alpha[2] : 0.;
      t->ScintE.nPE4 = gaus_eta[3] > 0. ? t->ScintE.e4 * gaus_eta[3] * alpha[3] : 0.;
      
      t->ScintE.de1 = t->ScintE.nPE1 > 0. ? t->ScintE.e1/sqrt(t->ScintE.nPE1) : 0.;
      t->ScintE.de2 = t->ScintE.nPE2 > 0. ? t->ScintE.e2/sqrt(t->ScintE.nPE2) : 0.;
      t->ScintE.de3 = t->ScintE.nPE3 > 0. ? t->ScintE.e3/sqrt(t->ScintE.nPE3) : 0.;
      t->ScintE.de4 = t->ScintE.nPE4 > 0. ? t->ScintE.e4/sqrt(t->ScintE.nPE4) : 0.;
      
      
      t->ScintW.e1 = linearityCurve.applyLinCurve(4,t->ScintW.q1) * epGain[4];
      t->ScintW.e2 = linearityCurve.applyLinCurve(5,t->ScintW.q2) * epGain[5];
      t->ScintW.e3 = linearityCurve.applyLinCurve(6,t->ScintW.q3) * epGain[6];
      t->ScintW.e4 = linearityCurve.applyLinCurve(7,t->ScintW.q4) * epGain[7];
      
      t->ScintW.e1 = ( gaus_eta[4]>0. && t->ScintW.e1>0. ) ? t->ScintW.e1 / gaus_eta[4] : 0.;
      t->ScintW.e2 = ( gaus_eta[5]>0. && t->ScintW.e2>0. ) ? t->ScintW.e2 / gaus_eta[5] : 0.;
      t->ScintW.e3 = ( gaus_eta[6]>0. && t->ScintW.e3>0. ) ? t->ScintW.e3 / gaus_eta[6] : 0.;
      t->ScintW.e4 = ( gaus_eta[7]>0. && t->ScintW.e4>0. ) ? t->ScintW.e4 / gaus_eta[7] : 0.;
      
      t->ScintW.nPE1 = gaus_eta[4] > 0. ? t->ScintW.e1 * gaus_eta[4] * alpha[4] : 0.;
      t->ScintW.nPE2 = gaus_eta[5] > 0. ? t->ScintW.e2 * gaus_eta[5] * alpha[5] : 0.;
      t->ScintW.nPE3 = gaus_eta[6] > 0. ? t->ScintW.e3 * gaus_eta[6] * alpha[6] : 0.;
      t->ScintW.nPE4 = gaus_eta[7] > 0. ? t->ScintW.e4 * gaus_eta[7] * alpha[7] : 0.;
      
      t->ScintW.de1 = t->ScintW.nPE1 > 0. ? t->ScintW.e1/sqrt(t->ScintW.nPE1) : 0.;
      t->ScintW.de2 = t->ScintW.nPE2 > 0. ? t->ScintW.e2/sqrt(t->ScintW.nPE2) : 0.;
      t->ScintW.de3 = t->ScintW.nPE3 > 0. ? t->ScintW.e3/sqrt(t->ScintW.nPE3) : 0.;
      t->ScintW.de4 = t->ScintW.nPE4 > 0. ? t->ScintW.e4/sqrt(t->ScintW.nPE4) : 0.;
      
      //std::cout << "Made it here" << std::endl;
      
      
      //Calculate the weighted energy on a side
      
      //EAST
      numer = 0.;
      numer = ( (pmtQuality[0] && t->ScintE.nPE1>0. ? t->ScintE.nPE1 : 0.) +
		(pmtQuality[1] && t->ScintE.nPE2>0. ? t->ScintE.nPE2 : 0.) + 
		(pmtQuality[2] && t->ScintE.nPE3>0. ? t->ScintE.nPE3 : 0.) + 
		(pmtQuality[3] && t->ScintE.nPE4>0. ? t->ScintE.nPE4 : 0.) );
      
      denom = 0.;
      denom  = ( (pmtQuality[0] && t->ScintE.nPE1>0. ? alpha[0] * gaus_eta[0] : 0.) +
		 (pmtQuality[1] && t->ScintE.nPE2>0. ? alpha[1] * gaus_eta[1] : 0.) +
		 (pmtQuality[2] && t->ScintE.nPE3>0. ? alpha[2] * gaus_eta[2] : 0.) + 
		 (pmtQuality[3] && t->ScintE.nPE4>0. ? alpha[3] * gaus_eta[3] : 0.) ); 
      
      t->ScintE.energy = t->EvisE = (denom!=0. ? numer/denom : 0.);
      t->ScintE.denergy = (denom!=0. ? sqrt(t->ScintE.energy/denom) : 0.);
      
      //WEST
      numer = denom = 0.;
      
      numer = ( (pmtQuality[4] && t->ScintW.nPE1>0. ? t->ScintW.nPE1 : 0.) +
		(pmtQuality[5] && t->ScintW.nPE2>0. ? t->ScintW.nPE2 : 0.) + 
		(pmtQuality[6] && t->ScintW.nPE3>0. ? t->ScintW.nPE3 : 0.) + 
		(pmtQuality[7] && t->ScintW.nPE4>0. ? t->ScintW.nPE4 : 0.) );
      
      denom  = ( (pmtQuality[4] && t->ScintW.nPE1>0. ? alpha[4] * gaus_eta[4] : 0.) +
		 (pmtQuality[5] && t->ScintW.nPE2>0. ? alpha[5] * gaus_eta[5] : 0.) +
		 (pmtQuality[6] && t->ScintW.nPE3>0. ? alpha[6] * gaus_eta[6] : 0.) + 
		 (pmtQuality[7] && t->ScintW.nPE4>0. ? alpha[7] * gaus_eta[7] : 0.) ); 
      
      
      t->ScintW.energy = t->EvisW = (denom!=0. ? numer/denom : 0.);
      t->ScintW.denergy = (denom!=0. ? sqrt(t->ScintW.energy/denom) : 0.);
      
      
      // Determine the reconstructed energy
    
      typeIndex = t->Type==0 ? 0:(t->Type==1 ? 1:2); //for retrieving the parameters from EQ2Etrue
    
      totalEvis=0.;
    
      if (t->Side==0) {
	totalEvis = t->Type==1 ? (t->EvisE+t->EvisW):t->EvisE;
	if (t->EvisE>0. && totalEvis>0.) {
	  t->gaus_Erecon = eRecon.getErecon(0,typeIndex,totalEvis);
	}
	else t->gaus_Erecon=-1.;
      }
      if (t->Side==1) {
	totalEvis = t->Type==1 ? (t->EvisE+t->EvisW):t->EvisW;
	if (t->EvisW>0. && totalEvis>0.) {
	  t->gaus_Erecon = eRecon.getErecon(1,typeIndex,totalEvis);
	}
	else t->gaus_Erecon=-1.;
      }
      
      
      
      /////////////////////////////////////////////////////////////
      // Now for the real Erecon and all of the variables that will be saved to file
      
      t->ScintE.e1 = linearityCurve.applyLinCurve(0,t->ScintE.q1) * epGain[0];
      t->ScintE.e2 = linearityCurve.applyLinCurve(1,t->ScintE.q2) * epGain[1];
      t->ScintE.e3 = linearityCurve.applyLinCurve(2,t->ScintE.q3) * epGain[2];
      t->ScintE.e4 = linearityCurve.applyLinCurve(3,t->ScintE.q4) * epGain[3];
      
      t->ScintE.e1 = ( eta[0]>0. ) ? t->ScintE.e1 / eta[0] : 0.;
      t->ScintE.e2 = ( eta[1]>0. ) ? t->ScintE.e2 / eta[1] : 0.;
      t->ScintE.e3 = ( eta[2]>0. ) ? t->ScintE.e3 / eta[2] : 0.;
      t->ScintE.e4 = ( eta[3]>0. ) ? t->ScintE.e4 / eta[3] : 0.;
      
      t->ScintE.nPE1 = eta[0] > 0. ? t->ScintE.e1 * eta[0] * alpha[0] : 0.;
      t->ScintE.nPE2 = eta[1] > 0. ? t->ScintE.e2 * eta[1] * alpha[1] : 0.;
      t->ScintE.nPE3 = eta[2] > 0. ? t->ScintE.e3 * eta[2] * alpha[2] : 0.;
      t->ScintE.nPE4 = eta[3] > 0. ? t->ScintE.e4 * eta[3] * alpha[3] : 0.;
      
      t->ScintE.de1 = t->ScintE.nPE1 > 0. ? t->ScintE.e1/sqrt(t->ScintE.nPE1) : 0.;
      t->ScintE.de2 = t->ScintE.nPE2 > 0. ? t->ScintE.e2/sqrt(t->ScintE.nPE2) : 0.;
      t->ScintE.de3 = t->ScintE.nPE3 > 0. ? t->ScintE.e3/sqrt(t->ScintE.nPE3) : 0.;
      t->ScintE.de4 = t->ScintE.nPE4 > 0. ? t->ScintE.e4/sqrt(t->ScintE.nPE4) : 0.;
      
      
      t->ScintW.e1 = linearityCurve.applyLinCurve(4,t->ScintW.q1) * epGain[4];
      t->ScintW.e2 = linearityCurve.applyLinCurve(5,t->ScintW.q2) * epGain[5];
      t->ScintW.e3 = linearityCurve.applyLinCurve(6,t->ScintW.q3) * epGain[6];
      t->ScintW.e4 = linearityCurve.applyLinCurve(7,t->ScintW.q4) * epGain[7];
      
      t->ScintW.e1 = ( eta[4]>0. ) ? t->ScintW.e1 / eta[4] : 0.;
      t->ScintW.e2 = ( eta[5]>0. ) ? t->ScintW.e2 / eta[5] : 0.;
      t->ScintW.e3 = ( eta[6]>0. ) ? t->ScintW.e3 / eta[6] : 0.;
      t->ScintW.e4 = ( eta[7]>0. ) ? t->ScintW.e4 / eta[7] : 0.;
      
      t->ScintW.nPE1 = eta[4] > 0. ? t->ScintW.e1 * eta[4] * alpha[4] : 0.;
      t->ScintW.nPE2 = eta[5] > 0. ? t->ScintW.e2 * eta[5] * alpha[5] : 0.;
      t->ScintW.nPE3 = eta[6] > 0. ? t->ScintW.e3 * eta[6] * alpha[6] : 0.;
      t->ScintW.nPE4 = eta[7] > 0. ? t->ScintW.e4 * eta[7] * alpha[7] : 0.;
      
      t->ScintW.de1 = t->ScintW.nPE1 > 0. ? t->ScintW.e1/sqrt(t->ScintW.nPE1) : 0.;
      t->ScintW.de2 = t->ScintW.nPE2 > 0. ? t->ScintW.e2/sqrt(t->ScintW.nPE2) : 0.;
      t->ScintW.de3 = t->ScintW.nPE3 > 0. ? t->ScintW.e3/sqrt(t->ScintW.nPE3) : 0.;
      t->ScintW.de4 = t->ScintW.nPE4 > 0. ? t->ScintW.e4/sqrt(t->ScintW.nPE4) : 0.;
      

      // Fill bare scintillator branch with no endpoint gain
      t->ScintE_bare.q1 = t->ScintE.q1;
      t->ScintE_bare.q2 = t->ScintE.q2;
      t->ScintE_bare.q3 = t->ScintE.q3;
      t->ScintE_bare.q4 = t->ScintE.q4;

      t->ScintW_bare.q1 = t->ScintW.q1;
      t->ScintW_bare.q2 = t->ScintW.q2;
      t->ScintW_bare.q3 = t->ScintW.q3;
      t->ScintW_bare.q4 = t->ScintW.q4;

      t->ScintE_bare.e1 = linearityCurve.applyLinCurve(0,t->ScintE_bare.q1);
      t->ScintE_bare.e2 = linearityCurve.applyLinCurve(1,t->ScintE_bare.q2);
      t->ScintE_bare.e3 = linearityCurve.applyLinCurve(2,t->ScintE_bare.q3);
      t->ScintE_bare.e4 = linearityCurve.applyLinCurve(3,t->ScintE_bare.q4);
      
      t->ScintE_bare.e1 = ( eta[0]>0. ) ? t->ScintE_bare.e1 / eta[0] : 0.;
      t->ScintE_bare.e2 = ( eta[1]>0. ) ? t->ScintE_bare.e2 / eta[1] : 0.;
      t->ScintE_bare.e3 = ( eta[2]>0. ) ? t->ScintE_bare.e3 / eta[2] : 0.;
      t->ScintE_bare.e4 = ( eta[3]>0. ) ? t->ScintE_bare.e4 / eta[3] : 0.;
      
      t->ScintE_bare.nPE1 = eta[0] > 0. ? t->ScintE_bare.e1 * eta[0] * alpha[0] : 0.;
      t->ScintE_bare.nPE2 = eta[1] > 0. ? t->ScintE_bare.e2 * eta[1] * alpha[1] : 0.;
      t->ScintE_bare.nPE3 = eta[2] > 0. ? t->ScintE_bare.e3 * eta[2] * alpha[2] : 0.;
      t->ScintE_bare.nPE4 = eta[3] > 0. ? t->ScintE_bare.e4 * eta[3] * alpha[3] : 0.;
      
      t->ScintE_bare.de1 = t->ScintE_bare.nPE1 > 0. ? t->ScintE_bare.e1/sqrt(t->ScintE_bare.nPE1) : 0.;
      t->ScintE_bare.de2 = t->ScintE_bare.nPE2 > 0. ? t->ScintE_bare.e2/sqrt(t->ScintE_bare.nPE2) : 0.;
      t->ScintE_bare.de3 = t->ScintE_bare.nPE3 > 0. ? t->ScintE_bare.e3/sqrt(t->ScintE_bare.nPE3) : 0.;
      t->ScintE_bare.de4 = t->ScintE_bare.nPE4 > 0. ? t->ScintE_bare.e4/sqrt(t->ScintE_bare.nPE4) : 0.;
      
      
      t->ScintW_bare.e1 = linearityCurve.applyLinCurve(4,t->ScintW_bare.q1);
      t->ScintW_bare.e2 = linearityCurve.applyLinCurve(5,t->ScintW_bare.q2);
      t->ScintW_bare.e3 = linearityCurve.applyLinCurve(6,t->ScintW_bare.q3);
      t->ScintW_bare.e4 = linearityCurve.applyLinCurve(7,t->ScintW_bare.q4);
      
      t->ScintW_bare.e1 = ( eta[4]>0. ) ? t->ScintW_bare.e1 / eta[4] : 0.;
      t->ScintW_bare.e2 = ( eta[5]>0. ) ? t->ScintW_bare.e2 / eta[5] : 0.;
      t->ScintW_bare.e3 = ( eta[6]>0. ) ? t->ScintW_bare.e3 / eta[6] : 0.;
      t->ScintW_bare.e4 = ( eta[7]>0. ) ? t->ScintW_bare.e4 / eta[7] : 0.;
      
      t->ScintW_bare.nPE1 = eta[4] > 0. ? t->ScintW_bare.e1 * eta[4] * alpha[4] : 0.;
      t->ScintW_bare.nPE2 = eta[5] > 0. ? t->ScintW_bare.e2 * eta[5] * alpha[5] : 0.;
      t->ScintW_bare.nPE3 = eta[6] > 0. ? t->ScintW_bare.e3 * eta[6] * alpha[6] : 0.;
      t->ScintW_bare.nPE4 = eta[7] > 0. ? t->ScintW_bare.e4 * eta[7] * alpha[7] : 0.;
      
      t->ScintW_bare.de1 = t->ScintW_bare.nPE1 > 0. ? t->ScintW_bare.e1/sqrt(t->ScintW_bare.nPE1) : 0.;
      t->ScintW_bare.de2 = t->ScintW_bare.nPE2 > 0. ? t->ScintW_bare.e2/sqrt(t->ScintW_bare.nPE2) : 0.;
      t->ScintW_bare.de3 = t->ScintW_bare.nPE3 > 0. ? t->ScintW_bare.e3/sqrt(t->ScintW_bare.nPE3) : 0.;
      t->ScintW_bare.de4 = t->ScintW_bare.nPE4 > 0. ? t->ScintW_bare.e4/sqrt(t->ScintW_bare.nPE4) : 0.;

      //std::cout << "Made it here" << std::endl;
      
      
      //Calculate the weighted energy on a side
      
      //EAST
      numer = 0.;
      numer = ( (pmtQuality[0] ? t->ScintE.nPE1 : 0.) +
		(pmtQuality[1] ? t->ScintE.nPE2 : 0.) + 
		(pmtQuality[2] ? t->ScintE.nPE3 : 0.) + 
		(pmtQuality[3] ? t->ScintE.nPE4 : 0.) );
      
      denom = 0.;
      denom  = ( (pmtQuality[0] ? alpha[0] * eta[0] : 0.) +
		 (pmtQuality[1] ? alpha[1] * eta[1] : 0.) +
		 (pmtQuality[2] ? alpha[2] * eta[2] : 0.) + 
		 (pmtQuality[3] ? alpha[3] * eta[3] : 0.) ); 
      
      t->ScintE.energy = t->EvisE = (denom!=0. ? numer/denom : 0.);
      t->ScintE.denergy = (denom!=0. ? sqrt(t->ScintE.energy/denom) : 0.);
      
      //WEST
      numer = denom = 0.;
      
      numer = ( (pmtQuality[4] ? t->ScintW.nPE1 : 0.) +
		(pmtQuality[5] ? t->ScintW.nPE2 : 0.) + 
		(pmtQuality[6] ? t->ScintW.nPE3 : 0.) + 
		(pmtQuality[7] ? t->ScintW.nPE4 : 0.) );
      
      denom  = ( (pmtQuality[4] ? alpha[4] * eta[4] : 0.) +
		 (pmtQuality[5] ? alpha[5] * eta[5] : 0.) +
		 (pmtQuality[6] ? alpha[6] * eta[6] : 0.) + 
		 (pmtQuality[7] ? alpha[7] * eta[7] : 0.) ); 
      
      
      t->ScintW.energy = t->EvisW = (denom!=0. ? numer/denom : 0.);
      t->ScintW.denergy = (denom!=0. ? sqrt(t->ScintW.energy/denom) : 0.);
      
      
      // Determine the reconstructed energy
      
      typeIndex = t->Type==0 ? 0:(t->Type==1 ? 1:2); //for retrieving the parameters from EQ2Etrue
      
      totalEvis=0.;
      t->Erecon_ee = 0.;
      //Handling APD events
      if (t->PID==6) {
	if (t->PassedCathE && t->PassedCathW) {
	  typeIndex=2;
	  t->Type=2;
	  t->Side = t->EvisE>t->EvisW?0:1;
	} else if (t->PassedCathE) {
	  typeIndex=0;
	  t->Type=0;
	  t->Side = 0;
	}
	else if (t->PassedCathW) {
	  typeIndex=0;
	  t->Type=0;
	  t->Side = 1;
	} else t->Side=2; //This won't create an Erecon.
	
      }

      if (t->Side==0) {
	totalEvis = t->Type==1 ? (t->EvisE+t->EvisW):t->EvisE;
	if (t->EvisE>0. && totalEvis>0.) {
	  t->Erecon = eRecon.getErecon(0,typeIndex,totalEvis);
	}
	else t->Erecon=-1.;
      }
      if (t->Side==1) {
	totalEvis = t->Type==1 ? (t->EvisE+t->EvisW):t->EvisW;
	if (t->EvisW>0. && totalEvis>0.) {
	  t->Erecon = eRecon.getErecon(1,typeIndex,totalEvis);
	}
	else t->Erecon=-1.;
      }
      
      if (t->Type==1 && t->EvisW>0. && t->EvisE>0.) {
	t->Erecon_ee = eRecon.getErecon(0,0,t->EvisE) + eRecon.getErecon(1,0,t->EvisW);
      }

    }
    else if (t->PID==0) {
      
      eta = posmap.getInterpolatedEta(0., 0., 0., 0.);
      //eta = posmap.getInterpolatedEta(xEast[0], yEast[0], xWest[0], yWest[0]);
      
      t->ScintE.e1 = linearityCurve.applyLinCurve(0,t->ScintE.q1);
      t->ScintE.e2 = linearityCurve.applyLinCurve(1,t->ScintE.q2);
      t->ScintE.e3 = linearityCurve.applyLinCurve(2,t->ScintE.q3);
      t->ScintE.e4 = linearityCurve.applyLinCurve(3,t->ScintE.q4);
      
      t->ScintE.e1 = ( eta[0]>0. ) ? t->ScintE.e1 / eta[0] : 0.;
      t->ScintE.e2 = ( eta[1]>0. ) ? t->ScintE.e2 / eta[1] : 0.;
      t->ScintE.e3 = ( eta[2]>0. ) ? t->ScintE.e3 / eta[2] : 0.;
      t->ScintE.e4 = ( eta[3]>0. ) ? t->ScintE.e4 / eta[3] : 0.;
      
      t->ScintE.nPE1 = eta[0] > 0. ? t->ScintE.e1 * eta[0] * alpha[0] : 0.;
      t->ScintE.nPE2 = eta[1] > 0. ? t->ScintE.e2 * eta[1] * alpha[1] : 0.;
      t->ScintE.nPE3 = eta[2] > 0. ? t->ScintE.e3 * eta[2] * alpha[2] : 0.;
      t->ScintE.nPE4 = eta[3] > 0. ? t->ScintE.e4 * eta[3] * alpha[3] : 0.;
      
      t->ScintE.de1 = t->ScintE.nPE1 > 0. ? t->ScintE.e1/sqrt(t->ScintE.nPE1) : 0.;
      t->ScintE.de2 = t->ScintE.nPE2 > 0. ? t->ScintE.e2/sqrt(t->ScintE.nPE2) : 0.;
      t->ScintE.de3 = t->ScintE.nPE3 > 0. ? t->ScintE.e3/sqrt(t->ScintE.nPE3) : 0.;
      t->ScintE.de4 = t->ScintE.nPE4 > 0. ? t->ScintE.e4/sqrt(t->ScintE.nPE4) : 0.;
      
      
      t->ScintW.e1 = linearityCurve.applyLinCurve(4,t->ScintW.q1);
      t->ScintW.e2 = linearityCurve.applyLinCurve(5,t->ScintW.q2);
      t->ScintW.e3 = linearityCurve.applyLinCurve(6,t->ScintW.q3);
      t->ScintW.e4 = linearityCurve.applyLinCurve(7,t->ScintW.q4);
    
      t->ScintW.e1 = ( eta[4]>0. ) ? t->ScintW.e1 / eta[4] : 0.;
      t->ScintW.e2 = ( eta[5]>0. ) ? t->ScintW.e2 / eta[5] : 0.;
      t->ScintW.e3 = ( eta[6]>0. ) ? t->ScintW.e3 / eta[6] : 0.;
      t->ScintW.e4 = ( eta[7]>0. ) ? t->ScintW.e4 / eta[7] : 0.;
    
      t->ScintW.nPE1 = eta[4] > 0. ? t->ScintW.e1 * eta[4] * alpha[4] : 0.;
      t->ScintW.nPE2 = eta[5] > 0. ? t->ScintW.e2 * eta[5] * alpha[5] : 0.;
      t->ScintW.nPE3 = eta[6] > 0. ? t->ScintW.e3 * eta[6] * alpha[6] : 0.;
      t->ScintW.nPE4 = eta[7] > 0. ? t->ScintW.e4 * eta[7] * alpha[7] : 0.;
    
      t->ScintW.de1 = t->ScintW.nPE1 > 0. ? t->ScintW.e1/sqrt(t->ScintW.nPE1) : 0.;
      t->ScintW.de2 = t->ScintW.nPE2 > 0. ? t->ScintW.e2/sqrt(t->ScintW.nPE2) : 0.;
      t->ScintW.de3 = t->ScintW.nPE3 > 0. ? t->ScintW.e3/sqrt(t->ScintW.nPE3) : 0.;
      t->ScintW.de4 = t->ScintW.nPE4 > 0. ? t->ScintW.e4/sqrt(t->ScintW.nPE4) : 0.;
    
      //std::cout << "Made it here" << std::endl;
    
    
      //Calculate the weighted energy on a side
    
      //EAST
      double numer = 0.;
      numer = ( (pmtQuality[0] ? t->ScintE.nPE1 : 0.) +
		(pmtQuality[1] ? t->ScintE.nPE2 : 0.) + 
		(pmtQuality[2] ? t->ScintE.nPE3 : 0.) + 
		(pmtQuality[3] ? t->ScintE.nPE4 : 0.) );
    
      double denom = 0.;
      denom  = ( (pmtQuality[0] ? alpha[0] * eta[0] : 0.) +
		 (pmtQuality[1] ? alpha[1] * eta[1] : 0.) +
		 (pmtQuality[2] ? alpha[2] * eta[2] : 0.) + 
		 (pmtQuality[3] ? alpha[3] * eta[3] : 0.) ); 
    
      t->ScintE.energy = t->EvisE = (denom!=0. ? numer/denom : 0.);
      t->ScintE.denergy = (denom!=0. ? sqrt(t->ScintE.energy/denom) : 0.);
    
      //WEST
      numer = denom = 0.;
    
      numer = ( (pmtQuality[4] ? t->ScintW.nPE1 : 0.) +
		(pmtQuality[5] ? t->ScintW.nPE2 : 0.) + 
		(pmtQuality[6] ? t->ScintW.nPE3 : 0.) + 
		(pmtQuality[7] ? t->ScintW.nPE4 : 0.) );
    
      denom  = ( (pmtQuality[4] ? alpha[4] * eta[4] : 0.) +
		 (pmtQuality[5] ? alpha[5] * eta[5] : 0.) +
		 (pmtQuality[6] ? alpha[6] * eta[6] : 0.) + 
		 (pmtQuality[7] ? alpha[7] * eta[7] : 0.) ); 
    
    
      t->ScintW.energy = t->EvisW = (denom!=0. ? numer/denom : 0.);
      t->ScintW.denergy = (denom!=0. ? sqrt(t->ScintW.energy/denom) : 0.);
  
    
      // Determine the reconstructed energy
    
      Int_t typeIndex = 0; //for retrieving the parameters from EQ2Etrue
     
      if (t->Side==0) {
	if (t->EvisE>0.) {
	  t->Erecon = eRecon.getErecon(0,typeIndex,t->EvisE);
	}
	else t->Erecon=-1.;
      }
      if (t->Side==1) {
	if (t->EvisW>0.) {
	  t->Erecon = eRecon.getErecon(1,typeIndex,t->EvisW);
	}
	else t->Erecon=-1.;
      }

    }
      
    // Last thing to do for electrons is position correct the anode signal and
    // apply the wirechamber energy calibration
    
    // Get the position response
    std::vector <Double_t> etaMWPC = anodeMap.getInterpolatedEta(t->xE.center,t->yE.center,
								 t->xW.center,t->yW.center);
    t->AnodeE = t->AnodeE / etaMWPC[0];
    t->AnodeW = t->AnodeW / etaMWPC[1];
    
    t->EMWPC_E = mwpcCal.applyCal( 0, t->AnodeE ) ;
    t->EMWPC_W = mwpcCal.applyCal( 1, t->AnodeW ) ;
    
  
  
    // write out pedestal subtracted cathode values for all events
    
    for ( int ii = 0; ii<16; ++ii ) {
      t->Cathodes_Ex[ii] = t->Cathodes_Ex[ii] - pedPdc2[ii+16]; 
      t->Cathodes_Ey[ii] = t->Cathodes_Ey[ii] - pedPdc2[ii];
      t->Cathodes_Wx[ii] = t->Cathodes_Wx[ii] - pedPadc[ii+16];
      t->Cathodes_Wy[ii] = t->Cathodes_Wy[ii] - pedPadc[ii];
    }
    
    t->fillOutputTree();
    
  }
  // Write output ntuple
  t->writeOutputFile();
  
  delete t; //Closes files

  if ( checkIfReplayFileIsGood(std::string(tempOut)) != 1 ) {

    std::ofstream badRuns("badRuns.txt", std::fstream::app);
    badRuns << argv[1] << "\n";
    badRuns.close();

  }

  return 0;
}
int main(int argc, char *argv[])
{
  cout.setf(ios::fixed, ios::floatfield);
  cout.precision(12);

  cout << "Run " << argv[1] << " ..." << endl;
  cout << "... Applying Bi pulser gain corrections ..." << endl;

  // Read gain corrections file
  char tempFileGain[500];
  sprintf(tempFileGain, "%s/gain_bismuth_%s.dat",getenv("GAIN_BISMUTH"), argv[1]);
  cout << "... Reading: " << tempFileGain << endl;

  double fitMean[8], gainCorrection[8];
  ifstream fileGain(tempFileGain);
  for (int i=0; i<8; i++) {
    fileGain >> fitMean[i] >> gainCorrection[i];
  }
  cout << "...   PMT E1: " << gainCorrection[0] << endl;
  cout << "...   PMT E2: " << gainCorrection[1] << endl;
  cout << "...   PMT E3: " << gainCorrection[2] << endl;
  cout << "...   PMT E4: " << gainCorrection[3] << endl;
  cout << "...   PMT W1: " << gainCorrection[4] << endl;
  cout << "...   PMT W2: " << gainCorrection[5] << endl;
  cout << "...   PMT W3: " << gainCorrection[6] << endl;
  cout << "...   PMT W4: " << gainCorrection[7] << endl;

  // Open output ntuple
  char tempOut[500];
  sprintf(tempOut, "%s/replay_pass2_%s.root",getenv("REPLAY_PASS2"), argv[1]);
  //sprintf(tempOut, "replay_pass2_%s.root", argv[1]);
  DataTree *t = new DataTree();
  t->makeOutputTree(std::string(tempOut),"pass2");

  char tempIn[500];
  sprintf(tempIn, "%s/replay_pass1_%s.root", getenv("REPLAY_PASS1"),argv[1]);
  //sprintf(tempIn, "../replay_pass1/replay_pass1_%s.root", argv[1]);
  t->setupInputTree(std::string(tempIn),"pass1");

  int nEvents = t->getEntries();
  cout << "... Processing nEvents = " << nEvents << endl;

  // Loop over events
  for (Int_t i=0; i<nEvents; i++) {
    t->getEvent(i);

    // Apply gain correction factors
    t->ScintE.q1 = t->ScintE.q1*gainCorrection[0];
    t->ScintE.q2 = t->ScintE.q2*gainCorrection[1];
    t->ScintE.q3 = t->ScintE.q3*gainCorrection[2];
    t->ScintE.q4 = t->ScintE.q4*gainCorrection[3];

    t->ScintW.q1 = t->ScintW.q1*gainCorrection[4];
    t->ScintW.q2 = t->ScintW.q2*gainCorrection[5];
    t->ScintW.q3 = t->ScintW.q3*gainCorrection[6];
    t->ScintW.q4 = t->ScintW.q4*gainCorrection[7]; 

    t->fillOutputTree();
  }

  // Write output ntuple
  t->writeOutputFile();
  delete t;

  return 0;
}