Exemple #1
0
void MainWindow::dropEvent( QDropEvent *event )
{
	if (!event->mimeData()->hasFormat(MIMETYPE)) 
	{
		return;
	}

	auto &filenameBytes = event->mimeData()->data(MIMETYPE);
	auto &filename = QTextCodec::codecForName("utf-16")->toUnicode(filenameBytes);

	DataTree *tree = this->findChild<DataTree *>(tr("treeWidget"));
	tree->clearData();
	tree->loadData(filename);
}
Exemple #2
0
void MainWindow::onExportData()
{
	// 判断有无导出路径;
	auto comboBox_exportPaths = this->findChild<QComboBox *>(tr("comboBox_exportPaths"));
	const auto &exportPath = comboBox_exportPaths->currentText();
	if (exportPath.isEmpty())
	{
		QMessageBox::information(NULL, "information", "Please set export path first!", QMessageBox::Yes, QMessageBox::Yes);
		return;
	}

	DataTree *tree = this->findChild<DataTree *>(tr("treeWidget"));
	tree->exportData(exportPath);

	QMessageBox::information(NULL, "information", "export done", QMessageBox::Yes, QMessageBox::Yes);
}
Exemple #3
0
bool LocalMachine::init()
{
	if(m_initialized)
		return true;

	NotificationsManager::instance()->notify(_S("Initializing local machine..."));

	OS_ASSERT(m_id.empty());

	String filePath = utils::makeFilePath(Options::instance()->getDataPath(), FILENAME);

	DataTree dt;
	if(dt.load(filePath))
	{
		m_publicKey = dt.getV(PUBLIC_KEY);
		m_privateKey = dt.getV(PRIVATE_KEY);

		if(CryptManager::instance()->rsaCheckKeys(m_privateKey, m_publicKey))
		{
			// Carica l'id della macchina dopo aver verificato la validit delle chiavi
			m_id = dt.getV(ID);

			// Verifica che l'id sia stato archiviato correttamente
			if(validate() == false)
				m_id.clear();
		}
	}

	if(m_id.empty())
	{
		m_privateKey.clear();
		m_publicKey.clear();

		if(CryptManager::instance()->rsaGenerateKeys(rsaType4096, m_privateKey, m_publicKey) == false)
			return false;

		// L'ID della macchina  dato dall'hash della chiave pubblica
		m_id = P2PSystem::instance()->generateMachineID(m_publicKey);

		dt.setV(ID, m_id);
		dt.setV(PUBLIC_KEY, m_publicKey);
		dt.setV(PRIVATE_KEY, m_privateKey);

		if(dt.save(filePath) == false)
			return false;
	}

	m_initialized = true;

	return true;
}
Exemple #4
0
const std::vector<std::string> DataTree::getKeySet(const std::string& key)
{
	std::vector<std::string> keySet;

	if (key.empty())
	{
		return keySet;
	}

	DataTree* targetTree = traverse(splitKeys(key));
	if (targetTree == nullptr)
	{
		return keySet;
	}

	keySet = targetTree->getKeySet();

	return keySet;
}
Exemple #5
0
bool AppConfig::save() {
    DataTree cfg;

    cfg.rootNode()->setName("cubicsdr_config");
    
    if (winW.load() && winH.load()) {
        DataNode *window_node = cfg.rootNode()->newChild("window");
        
        *window_node->newChild("x") = winX.load();
        *window_node->newChild("y") = winY.load();
        *window_node->newChild("w") = winW.load();
        *window_node->newChild("h") = winH.load();

        *window_node->newChild("max") = winMax.load();
        *window_node->newChild("theme") = themeId.load();
        *window_node->newChild("snap") = snap.load();
        *window_node->newChild("center_freq") = centerFreq.load();
        *window_node->newChild("waterfall_lps") = waterfallLinesPerSec.load();
        *window_node->newChild("spectrum_avg") = spectrumAvgSpeed.load();
    }
    
    DataNode *devices_node = cfg.rootNode()->newChild("devices");

    std::map<std::string, DeviceConfig *>::iterator device_config_i;
    for (device_config_i = deviceConfig.begin(); device_config_i != deviceConfig.end(); device_config_i++) {
        DataNode *device_node = devices_node->newChild("device");
        device_config_i->second->save(device_node);
    }

    if (manualDevices.size()) {
        DataNode *manual_node = cfg.rootNode()->newChild("manual_devices");
        for (std::vector<SDRManualDef>::const_iterator i = manualDevices.begin(); i != manualDevices.end(); i++) {
            DataNode *rig_node = manual_node->newChild("device");
            *rig_node->newChild("factory") = i->factory;
            *rig_node->newChild("params") = i->params;
        }
    }
    
#ifdef USE_HAMLIB
    DataNode *rig_node = cfg.rootNode()->newChild("rig");
    *rig_node->newChild("model") = rigModel.load();
    *rig_node->newChild("rate") = rigRate.load();
    *rig_node->newChild("port") = rigPort;
#endif
    
    std::string cfgFileName = getConfigFileName();
    
    if (!cfg.SaveToFileXML(cfgFileName)) {
        std::cout << "Error saving :: configuration file '" << cfgFileName << "' is not writable!" << std::endl;
        return false;
    }

    return true;
}
Exemple #6
0
MainWindow::MainWindow(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);

	DataTree *tree = this->findChild<DataTree *>(tr("treeWidget"));

	QStringList headers;
	headers << tr("title"); 
	tree->setHeaderLabels(headers);

	tree->setHeaderHidden(true);


	auto exportButton = this->findChild<QPushButton *>(tr("pushButton_exportData"));
	if (exportButton)
	{
		this->connect(exportButton, SIGNAL(clicked()), this, SLOT(onExportData()));
	}

	auto setExportPathButton = this->findChild<QPushButton *>(tr("pushButton_setExportPath"));
	if (setExportPathButton)
	{
		this->connect(setExportPathButton, SIGNAL(clicked()), this, SLOT(onSetExportPath()));
	}

	auto helpButton = this->findChild<QPushButton *>(tr("pushButton_help"));
	if (helpButton)
	{
		this->connect(helpButton, SIGNAL(clicked()), this, SLOT(onHelp()));
	}

	this->setAcceptDrops(true);

	loadOpenedFileList();

	//QString filename = QObject::tr("D:\\dev\\project\\misc\\qt\\DataExporter\\data\\test.xlsx");
	//tree->loadData(filename);
}
Exemple #7
0
DataTree* DataTree::create(const std::string& fileName)
{
	if (fileName.empty())
	{
		return nullptr;
	}

	std::string fileData = std::string();
	std::ifstream file(fileName);

	if (file.is_open())
	{
		// Simply using while loop and getline to read file instead of using file size method because file size wasn't correct.
		std::string line;
		while (std::getline(file, line))
		{
			fileData += (line + "\n");
		}
	}

	if (fileData.empty() || fileData.size() <= 0)
	{
		//Data is empty or size is 0. 
		return nullptr;
	}

	DataTree* data = new DataTree("ROOT_KEY", "ROOT_VALUE");
	bool result = data->parse(fileData);

	if (result == false)
	{
		//Failed to parse
		delete data;
		return nullptr;
	}

	return data;
}
Exemple #8
0
bool AppConfig::save() {
    DataTree cfg;

    cfg.rootNode()->setName("cubicsdr_config");

    if (winW.load() && winH.load()) {
        DataNode *window_node = cfg.rootNode()->newChild("window");

        *window_node->newChild("x") = winX.load();
        *window_node->newChild("y") = winY.load();
        *window_node->newChild("w") = winW.load();
        *window_node->newChild("h") = winH.load();

        *window_node->newChild("max") = winMax.load();
        *window_node->newChild("theme") = themeId.load();
        *window_node->newChild("snap") = snap.load();
        *window_node->newChild("center_freq") = centerFreq.load();
    }

    DataNode *devices_node = cfg.rootNode()->newChild("devices");

    std::map<std::string, DeviceConfig *>::iterator device_config_i;
    for (device_config_i = deviceConfig.begin(); device_config_i != deviceConfig.end(); device_config_i++) {
        DataNode *device_node = devices_node->newChild("device");
        device_config_i->second->save(device_node);
    }

    std::string cfgFileName = getConfigFileName();

    if (!cfg.SaveToFileXML(cfgFileName)) {
        std::cout << "Error saving :: configuration file '" << cfgFileName << "' is not writable!" << std::endl;
        return false;
    }

    return true;
}
Exemple #9
0
// read file type and id name without actually opening it
bool Resource::GetFileHeader(const std::string& filename, DataTree &fileHeader_out)
{
	char *hdr_serialized;
	long dataSize,headerSize;
	
	ifstream fin(filename.c_str(), ios::binary);
	
	fin.read((char *)&headerSize, sizeof(long));
	fin.read((char *)&dataSize, sizeof(long));
	
	hdr_serialized = new char[headerSize];
	fin.read(hdr_serialized,headerSize);
	
	fileHeader_out.setSerialized(hdr_serialized);
	
	fin.close();
	
	delete hdr_serialized;

	return true;
}
Exemple #10
0
bool SnapLog::Impl::Serialize(
    const DataTree &data_tree,
    const map<uint64, uint64> &session_timeouts,
    string *output) {
  global::SnapLogFileHeader header;
  header.magic = atol(kSnapLogFileHeaderMagic);
  header.version = kLogVersion;
  header.dbid = kDbId;
  global::SessionList session_list;
  ASSERT_TRUE(SerializeSessionList(session_timeouts, &session_list));
  header.session_size = session_list.ByteSize();
  string header_content;
  ASSERT_TRUE(header.Serialize(&header_content));
  string session_list_content;
  ASSERT_TRUE(session_list.SerializeToString(&session_list_content));
  string data_tree_content;
  ASSERT_TRUE(data_tree.Serialize(&data_tree_content));
  *output = header_content;
  output->append(session_list_content);
  output->append(data_tree_content);
  return true;
}
Exemple #11
0
bool AppConfig::save() {
    DataTree cfg;

    cfg.rootNode()->setName("cubicsdr_config");
    
    if (winW.load() && winH.load()) {
        DataNode *window_node = cfg.rootNode()->newChild("window");
        
        *window_node->newChild("x") = winX.load();
        *window_node->newChild("y") = winY.load();
        *window_node->newChild("w") = winW.load();
        *window_node->newChild("h") = winH.load();

        *window_node->newChild("max") = winMax.load();
        *window_node->newChild("tips") = showTips.load();
        *window_node->newChild("perf_mode") = (int)perfMode.load();
        *window_node->newChild("theme") = themeId.load();
        *window_node->newChild("font_scale") = fontScale.load();
        *window_node->newChild("snap") = snap.load();
        *window_node->newChild("center_freq") = centerFreq.load();
        *window_node->newChild("waterfall_lps") = waterfallLinesPerSec.load();
        *window_node->newChild("spectrum_avg") = spectrumAvgSpeed.load();
        *window_node->newChild("modemprops_collapsed") = modemPropsCollapsed.load();;
        *window_node->newChild("db_offset") = dbOffset.load();

        *window_node->newChild("main_split") = mainSplit.load();
        *window_node->newChild("vis_split") = visSplit.load();
        *window_node->newChild("bookmark_split") = bookmarkSplit.load();
        *window_node->newChild("bookmark_visible") = bookmarksVisible.load();
    }
    
	//Recording settings:
    DataNode *rec_node = cfg.rootNode()->newChild("recording");
    *rec_node->newChild("path") = recordingPath;
	*rec_node->newChild("squelch") = recordingSquelchOption;
	*rec_node->newChild("file_time_limit") = recordingFileTimeLimitSeconds;
    
    DataNode *devices_node = cfg.rootNode()->newChild("devices");

    std::map<std::string, DeviceConfig *>::iterator device_config_i;
    for (device_config_i = deviceConfig.begin(); device_config_i != deviceConfig.end(); device_config_i++) {
        DataNode *device_node = devices_node->newChild("device");
        device_config_i->second->save(device_node);
    }

    if (manualDevices.size()) {
        DataNode *manual_node = cfg.rootNode()->newChild("manual_devices");
        for (std::vector<SDRManualDef>::const_iterator i = manualDevices.begin(); i != manualDevices.end(); i++) {
            DataNode *rig_node = manual_node->newChild("device");
            *rig_node->newChild("factory") = i->factory;
            *rig_node->newChild("params") = i->params;
        }
    }
    
#ifdef USE_HAMLIB
    DataNode *rig_node = cfg.rootNode()->newChild("rig");
    *rig_node->newChild("enabled") = rigEnabled.load()?1:0;
    *rig_node->newChild("model") = rigModel.load();
    *rig_node->newChild("rate") = rigRate.load();
    *rig_node->newChild("port") = rigPort;
    *rig_node->newChild("control") = rigControlMode.load()?1:0;
    *rig_node->newChild("follow") = rigFollowMode.load()?1:0;
    *rig_node->newChild("center_lock") = rigCenterLock.load()?1:0;
    *rig_node->newChild("follow_modem") = rigFollowModem.load()?1:0;
#endif
    
    std::string cfgFileName = getConfigFileName();
    
    if (!cfg.SaveToFileXML(cfgFileName)) {
        std::cout << "Error saving :: configuration file '" << cfgFileName << "' is not writable!" << std::endl;
        return false;
    }

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

  // Prompt for filename of run numbers
  int iXeRunPeriod;
  cout << "Enter Xenon run period: " << endl;
  cin  >> iXeRunPeriod;
  cout << endl;

  /*bool allResponseClasses = true;
  int numResponseClasses = 0;
  vector <int> responseClasses;
  
  cout << "All Response Classes? (true=1/false=0): " << endl;
  cin  >> allResponseClasses;
  cout << endl;

  if (!allResponseClasses) {
    
    cout << "Enter number of response classes: " << endl;
    cin >> numResponseClasses;
    cout << endl;

    if (numResponseClasses<1 || numResponseClasses>9) {
      cout << "Bad number of response classes to include!!\n";
      exit(1);
    }
    responseClasses.resize(numResponseClasses,0);
    char quest[30];
    for (int i=0; i<numResponseClasses; i++) {
      sprintf(quest,"Enter class #%i: ",i+1);
      cout << quest;
      cin >> responseClasses[i];
      cout << endl;
      
      if (responseClasses[i]<0 || responseClasses[i]>8) {
	cout << "You entered a non-existent response class!\n";
	exit(1);
      }
    }
    }*/


  int nRuns = 0;
  int runList[500];

  char temp[500];
  sprintf(temp, "%s/run_lists/Xenon_Calibration_Run_Period_%i.dat", getenv("ANALYSIS_CODE"),iXeRunPeriod);
  ifstream fileRuns(temp);

  int ii = 0;
  while (fileRuns >> runList[ii]) {
    ii++;
    nRuns++;
  }

  cout << "... Number of runs: " << nRuns << endl;
  for (int i=0; i<nRuns; i++) {
    cout << runList[i] << endl;
  }

  
  double xyBinWidth = 5.; //2.5;
  PositionMap posmap(xyBinWidth,50.);
  posmap.setRCflag(false); //telling the position map to not use the RC choices
  Int_t nBinsXY = posmap.getNbinsXY();
  

  // Open output ntuple
  string tempOutBase;
  string tempOut;
  //sprintf(tempOut, "position_map_%s.root", argv[1]);
  tempOutBase = "position_map_" + itos(iXeRunPeriod);
  /*if (!allResponseClasses) {
    tempOutBase+="_RC_";
    for (int i=0; i< numResponseClasses; i++) {
      tempOutBase+=itos(responseClasses[i]);
    }
    }*/
  tempOut =  getenv("POSITION_MAPS")+tempOutBase+"_"+ftos(xyBinWidth)+"mm.root";
  TFile *fileOut = new TFile(tempOut.c_str(),"RECREATE");

  // Output histograms
  int nPMT = 8;
  int nBinHist = 4100;//1025;

  TH1D *hisxy[nPMT][nBinsXY][nBinsXY];
  char *hisxyName = new char[10];

  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<posmap.getNbinsXY(); i++) {
      for (int j=0; j<posmap.getNbinsXY(); j++) {
        if (p == 0)
          sprintf(hisxyName, "e0_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 1)
          sprintf(hisxyName, "e1_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 2)
          sprintf(hisxyName, "e2_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 3)
          sprintf(hisxyName, "e3_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 4)
          sprintf(hisxyName, "w0_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 5)
          sprintf(hisxyName, "w1_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 6)
          sprintf(hisxyName, "w2_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));
        if (p == 7)
          sprintf(hisxyName, "w3_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j));

        hisxy[p][i][j] = new TH1D(hisxyName, "", nBinHist,-100.,4000.0);

      }
    }
  }

  // Loop through input ntuples
  char tempIn[500];
  for (int i=0; i<nRuns; i++) {

    // Open input ntuple
    sprintf(tempIn, "%s/replay_pass2_%i.root",getenv("REPLAY_PASS2"), runList[i]);
    DataTree *t = new DataTree();
    t->setupInputTree(std::string(tempIn),"pass2");

    if ( !t->inputTreeIsGood() ) { 
      std::cout << "Skipping " << tempIn << "... Doesn't exist or couldn't be opened.\n";
      continue;
    }

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


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

      // Select Type 0 events
      if (t->PID != 1) continue;
      if (t->Type != 0) continue;

      //Cut out clipped events
      if ( t->Side==0 && ( t->xE.nClipped>0 || t->yE.nClipped>0 || t->xeRC<1 || t->xeRC>4 || t->yeRC<1 || t->yeRC>4 ) ) continue;
      else if ( t->Side==1 && ( t->xW.nClipped>0 || t->yW.nClipped>0 || t->xwRC<1 || t->xwRC>4 || t->ywRC<1 || t->ywRC>4) ) continue;

		
      
      /*bool moveOnX = true, moveOnY=true; // Determining if the event is of the correct response class in x and y
     
	//Swank addition: Wire Chamber Response class. 
	for (int j=0; j<numResponseClasses; j++) {
	  if (t->xeRC == responseClasses[j]) {moveOnX=false;}
	  if (t->yeRC == responseClasses[j]) {moveOnY=false;}
	}
      
	if (moveOnX || moveOnY) continue;*/

      // Type 0 East Trigger
      int intBinX, intBinY; 
      
      if (t->Side == 0) {
	
	intBinX = posmap.getBinNumber(t->xE.center);
        intBinY = posmap.getBinNumber(t->yE.center);

        // Fill PMT histograms
        if (intBinX>-1 && intBinY>-1) hisxy[0][intBinX][intBinY]->Fill(t->ScintE.q1);
        if (intBinX>-1 && intBinY>-1) hisxy[1][intBinX][intBinY]->Fill(t->ScintE.q2);
        if (intBinX>-1 && intBinY>-1) hisxy[2][intBinX][intBinY]->Fill(t->ScintE.q3);
        if (intBinX>-1 && intBinY>-1) hisxy[3][intBinX][intBinY]->Fill(t->ScintE.q4);
      }

      // Type 0 West Trigger
      //moveOnX=moveOnY=true;
      else if (t->Side == 1) {

	//Swank Only Allow triangles!!!	  	
	//for (int j=0; j<numResponseClasses; j++) {
	// if (t->xwRC == responseClasses[j]) {moveOnX=false;}
	// if (t->ywRC == responseClasses[j]) {moveOnY=false;}
	//}
      
	//if (moveOnX || moveOnY) continue;
	
        intBinX = posmap.getBinNumber(t->xW.center);
        intBinY = posmap.getBinNumber(t->yW.center);

	// Fill PMT histograms 
        if (intBinX>-1 && intBinY>-1) hisxy[4][intBinX][intBinY]->Fill(t->ScintW.q1);
        if (intBinX>-1 && intBinY>-1) hisxy[5][intBinX][intBinY]->Fill(t->ScintW.q2);
        if (intBinX>-1 && intBinY>-1) hisxy[6][intBinX][intBinY]->Fill(t->ScintW.q3);
        if (intBinX>-1 && intBinY>-1) hisxy[7][intBinX][intBinY]->Fill(t->ScintW.q4);
      }


    }

    // Close input ntuple
    delete t;

  }


  //Rebinning the histograms based on the mean value...
  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {	

	hisxy[p][i][j]->GetXaxis()->SetRange(1,nBinHist);
	Double_t mean = hisxy[p][i][j]->GetMean();
	hisxy[p][i][j]->GetXaxis()->SetRange(0,nBinHist);
	double nGroup = 4.*mean/200.;
	nGroup = nGroup>1. ? nGroup : 1.;
	hisxy[p][i][j]->Rebin((int)nGroup);
	
      }
    }
  }

  // Extracting mean from 200 keV peak 

  // Define fit ranges
  double xLowBin[nPMT][nBinsXY][nBinsXY];
  double xHighBin[nPMT][nBinsXY][nBinsXY];
  double xLow[nPMT][nBinsXY][nBinsXY];
  double xHigh[nPMT][nBinsXY][nBinsXY];
  int maxBin[nPMT][nBinsXY][nBinsXY];
  double maxCounts[nPMT][nBinsXY][nBinsXY];
  double binCenterMax[nPMT][nBinsXY][nBinsXY];
  double meanVal[nPMT][nBinsXY][nBinsXY]; // Holds the mean of the distribution as defined by first fitting the peak
  double fitMean[nPMT][nBinsXY][nBinsXY]; // Holds the mean of the low energy peak
  double fitSigma[nPMT][nBinsXY][nBinsXY]; // Holds the sigma of the low energy peak
  double endpoint[nPMT][nBinsXY][nBinsXY]; // Holds the endpoint


  /////// First determine roughly where the low energy peak is
  TSpectrum *spec;

  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {	
	
	double r = sqrt(power(posmap.getBinCenter(j),2)+power(posmap.getBinCenter(i),2));
	
        // Find bin with maximum content
	hisxy[p][i][j]->GetXaxis()->SetRange(2,nBinHist);
        maxBin[p][i][j] = hisxy[p][i][j]->GetMaximumBin();
        maxCounts[p][i][j] = hisxy[p][i][j]->GetBinContent(maxBin[p][i][j]);
        binCenterMax[p][i][j] = hisxy[p][i][j]->GetBinCenter(maxBin[p][i][j]);
	
	  
	if (r<=(50.+2*xyBinWidth))
	      {
		spec = new TSpectrum(20);
		Int_t npeaks = spec->Search(hisxy[p][i][j],1.5,"",0.5);
		
		if (npeaks==0)
		  {
		    cout << "No peaks identified at PMT" << p << " position " << posmap.getBinCenter(i) << ", " << posmap.getBinCenter(j) << endl;
		  }
		else
		  {
		    Float_t *xpeaks = spec->GetPositionX(); // Note that newer versions of ROOT return a pointer to double...
		    TAxis *xaxis = (TAxis*)(hisxy[p][i][j]->GetXaxis());
		    Int_t peakBin=0;
		    Double_t BinSum=0.;
		    Double_t BinSumHold = 0.;
		    Int_t maxPeak=0.;
		    for (int pk=0;pk<npeaks;pk++) {
		      peakBin = xaxis->FindBin(xpeaks[pk]);
		      //Sum over 3 center bins of peak and compare to previos BinSum to see which peak is higher
		      BinSum = hisxy[p][i][j]->GetBinContent(peakBin) + hisxy[p][i][j]->GetBinContent(peakBin-1) + hisxy[p][i][j]->GetBinContent(peakBin+1);
		      if (BinSum>BinSumHold) {
			BinSumHold=BinSum;
			maxPeak=pk;
		      }
		    }
		    binCenterMax[p][i][j] = xpeaks[maxPeak];
		  }
		delete spec;
	      }
	xLow[p][i][j] = binCenterMax[p][i][j]*2./3.;
	xHigh[p][i][j] = 1.5*binCenterMax[p][i][j];

	
      }
    }
  }
  
  //////// Now fit the histograms for the peak

  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {	

	if ( hisxy[p][i][j]->Integral() > 500.) {// && r<=(50.+2*xBinWidth)) {

	  SinglePeakHist sing(hisxy[p][i][j], xLow[p][i][j], xHigh[p][i][j], true, 5, 0.8, 1.);

	  if (sing.isGoodFit() && sing.ReturnMean()>xLow[p][i][j] && sing.ReturnMean()<xHigh[p][i][j]) {
	    fitMean[p][i][j] = sing.ReturnMean();
	    fitSigma[p][i][j] = sing.ReturnSigma();
	  }

	  else  {
	    cout << "Can't converge on peak in PMT " << p << " at (" << posmap.getBinCenter(i) << ", " << posmap.getBinCenter(j) << "). Trying one more time......" << endl;
	    sing.SetRangeMin(xLow[p][i][j]);
	    sing.SetRangeMax(xHigh[p][i][j]);
	    sing.FitHist((double)maxBin[p][i][j], hisxy[p][i][j]->GetMean()/5., hisxy[p][i][j]->GetBinContent(maxBin[p][i][j]));

	    if (sing.isGoodFit() && sing.ReturnMean()>xLow[p][i][j] && sing.ReturnMean()<xHigh[p][i][j]) { 
	      fitMean[p][i][j] = sing.ReturnMean();
	      fitSigma[p][i][j] = sing.ReturnSigma();
	    }
	    else {
	      fitMean[p][i][j] = hisxy[p][i][j]->GetMean()/1.8;
	      int meanBin = hisxy[p][i][j]->GetXaxis()->FindBin(fitMean[p][i][j]);
	      int counts_check = hisxy[p][i][j]->GetBinContent(meanBin);
	      int counts = counts_check;
	      int bin=0;
	      if ( counts_check > 10 ) {
		while (counts>0.6*counts_check) {
		  bin++;
		  counts = hisxy[p][i][j]->GetBinContent(meanBin+bin);
		}
	      }
	  
	      xHighBin[p][i][j] = (meanBin+bin) < hisxy[p][i][j]->GetNbinsX()/3 ? (meanBin+bin): meanBin;
	      fitSigma[p][i][j] = hisxy[p][i][j]->GetBinCenter(xHighBin[p][i][j]) - fitMean[p][i][j];

	      cout << "Can't converge on peak in PMT " << p << " at bin (" << posmap.getBinCenter(i) << ", " << posmap.getBinCenter(j) << "). ";
	      cout << "**** replaced fit mean with hist_mean/1.8 " << fitMean[p][i][j] << endl;
	    }
	  }
	}
	else { 
	  fitMean[p][i][j] = hisxy[p][i][j]->GetMean()/1.8;
	  //if ( fitMean[p][i][j]>xLow[p][i][j] && fitMean[p][i][j]<xHigh[p][i][j] ) 
	  cout << "**** replaced fit mean with hist_mean/1.8 " << fitMean[p][i][j] << endl;
	  //else { 
	  //fitMean[p][i][j] = binCenterMax[p][i][j];
	  //cout << "**** replaced fit mean with binCenterMax " << fitMean[p][i][j] << endl;
	  //}
	  int meanBin = hisxy[p][i][j]->GetXaxis()->FindBin(fitMean[p][i][j]);
	  int counts_check = hisxy[p][i][j]->GetBinContent(meanBin);
	  int counts = counts_check;
	  int bin=0;
	  double frac = exp(-1/2.); // This should be the fraction of events for a gaussian at 1 sigma
	  if ( counts_check > 10 ) {
	    while (counts>frac*counts_check) {
	      bin++;
	      counts = hisxy[p][i][j]->GetBinContent(meanBin+bin);
	    }
	  }	  
	  xHighBin[p][i][j] = (meanBin+bin) < hisxy[p][i][j]->GetNbinsX()/3 ? (meanBin+bin): meanBin;
	  fitSigma[p][i][j] = hisxy[p][i][j]->GetBinCenter(xHighBin[p][i][j]) - fitMean[p][i][j];	 
	}

      }
    }
  }

  fileOut->Write(); // Writing the histograms with the peaks to file

  ////////// Now determine the mean of the Xe distribution in every position bin above the peak to avoid
  ////////// trigger effects
  
  double nSigmaFromMean = 1.5; // This is how far over from the peak we are starting the sum of the spectra

  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {

	hisxy[p][i][j]->GetXaxis()->SetRange(hisxy[p][i][j]->GetXaxis()->FindBin(fitMean[p][i][j]+nSigmaFromMean*fitSigma[p][i][j]), hisxy[p][i][j]->GetNbinsX()-1);
	meanVal[p][i][j] = hisxy[p][i][j]->GetMean();
	hisxy[p][i][j]->GetXaxis()->SetRange(0, hisxy[p][i][j]->GetNbinsX()); // Set the range back to the full range

      }
    }
  }

  ////////// Now determine the endpoint of the Xe distribution in every position bin

  double lowerBoundMult = 1.;
  double upperBoundMult = 2.;

  TFile *epfile = new TFile(TString::Format("%s/%s_%smm_endpoints.root",getenv("POSITION_MAPS"),tempOutBase.c_str(),ftos(xyBinWidth).c_str()),"RECREATE");

  TGraphErrors epgraph;
  
  KurieFitter kf;
  
  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {

	kf.FitSpectrum(hisxy[p][i][j], lowerBoundMult*meanVal[p][i][j], upperBoundMult*meanVal[p][i][j], 1.);
	endpoint[p][i][j] = kf.returnK0();

	epgraph = kf.returnKuriePlot();
	epgraph.SetName(TString::Format("pmt%i_x%0.1f_y%0.1f",p,posmap.getBinCenter(i), posmap.getBinCenter(j)));
	epgraph.Write();

      }
    }
  }

  delete epfile;
  delete fileOut;


  ///////////////////////// Extract position maps for meanVal ///////////////////////////////
  double norm[nPMT];
  for (int p=0; p<nPMT; p++) {
    norm[p] = meanVal[p][nBinsXY/2][nBinsXY/2];
    cout << norm[p] << endl;
  }

  //Checking for weird outliers
  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {
	
	if ( meanVal[p][i][j]<(0.1*norm[p]) || meanVal[p][i][j]>(8.*norm[p]) ) 
	  meanVal[p][i][j] = (0.1*norm[p]);

      }
    }
  }

  double positionMap[nPMT][nBinsXY][nBinsXY];
  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {
        positionMap[p][i][j] = meanVal[p][i][j] / norm[p];
      }
    }
  }

  // Write position maps to file
  TString mapFile = TString::Format("%s/%s_%0.1fmm.dat", getenv("POSITION_MAPS"),tempOutBase.c_str(),xyBinWidth);
  ofstream outMap(mapFile.Data());

  for (int i=0; i<nBinsXY; i++) {
    for (int j=0; j<nBinsXY; j++) {
      outMap << posmap.getBinCenter(i) << "  "
             << posmap.getBinCenter(j) << "  "
             << positionMap[0][i][j] << "  "
             << positionMap[1][i][j] << "  "
             << positionMap[2][i][j] << "  "
             << positionMap[3][i][j] << "  "
             << positionMap[4][i][j] << "  "
             << positionMap[5][i][j] << "  "
             << positionMap[6][i][j] << "  "
             << positionMap[7][i][j] << endl;
    }
  }
  outMap.close();

  // Write norms to file
  TString normFile = TString::Format("%s/norm_%s_%0.1fmm.dat", getenv("POSITION_MAPS"),tempOutBase.c_str(),xyBinWidth);
  ofstream outNorm(normFile.Data());

  for (int p=0; p<nPMT; p++) {
    outNorm << norm[p] << endl;
  }
  outNorm.close();

  ///////////////////////// Extract position maps for peaks ///////////////////////////////

  for (int p=0; p<nPMT; p++) {
    norm[p] = fitMean[p][nBinsXY/2][nBinsXY/2];
    cout << norm[p] << endl;
  }

  //Checking for weird outliers
  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {
	
	if ( fitMean[p][i][j]<(0.1*norm[p]) || fitMean[p][i][j]>(8.*norm[p]) ) 
	  fitMean[p][i][j] = (0.1*norm[p]);

      }
    }
  }

  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {
        positionMap[p][i][j] = fitMean[p][i][j] / norm[p];
      }
    }
  }

  // Write position maps to file
  mapFile = TString::Format("%s/%s_%0.1fmm_peakFits.dat", getenv("POSITION_MAPS"),tempOutBase.c_str(),xyBinWidth);
  outMap.open(mapFile.Data());
  

  for (int i=0; i<nBinsXY; i++) {
    for (int j=0; j<nBinsXY; j++) {
      outMap << posmap.getBinCenter(i) << "  "
             << posmap.getBinCenter(j) << "  "
             << positionMap[0][i][j] << "  "
             << positionMap[1][i][j] << "  "
             << positionMap[2][i][j] << "  "
             << positionMap[3][i][j] << "  "
             << positionMap[4][i][j] << "  "
             << positionMap[5][i][j] << "  "
             << positionMap[6][i][j] << "  "
             << positionMap[7][i][j] << endl;
    }
  }
  outMap.close();


  ///////////////////////// Extract position maps for endpoints ///////////////////////////////

  for (int p=0; p<nPMT; p++) {
    norm[p] = endpoint[p][nBinsXY/2][nBinsXY/2];
    cout << norm[p] << endl;
  }

  //Checking for weird outliers
  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {
	
	if ( endpoint[p][i][j]<(0.1*norm[p]) || endpoint[p][i][j]>(8.*norm[p]) ) 
	  endpoint[p][i][j] = (0.1*norm[p]);

      }
    }
  }

  for (int p=0; p<nPMT; p++) {
    for (int i=0; i<nBinsXY; i++) {
      for (int j=0; j<nBinsXY; j++) {
        positionMap[p][i][j] = endpoint[p][i][j] / norm[p];
      }
    }
  }

  // Write position maps to file
  mapFile = TString::Format("%s/%s_%0.1fmm_endpoints.dat", getenv("POSITION_MAPS"),tempOutBase.c_str(),xyBinWidth);
  outMap.open(mapFile.Data());

  for (int i=0; i<nBinsXY; i++) {
    for (int j=0; j<nBinsXY; j++) {
      outMap << posmap.getBinCenter(i) << "  "
             << posmap.getBinCenter(j) << "  "
             << positionMap[0][i][j] << "  "
             << positionMap[1][i][j] << "  "
             << positionMap[2][i][j] << "  "
             << positionMap[3][i][j] << "  "
             << positionMap[4][i][j] << "  "
             << positionMap[5][i][j] << "  "
             << positionMap[6][i][j] << "  "
             << positionMap[7][i][j] << endl;
    }
  }
  outMap.close();



  return 0;
}
Exemple #13
0
bool AppConfig::load() {
    DataTree cfg;
    std::string cfgFileDir = getConfigDir();

    std::string cfgFileName = getConfigFileName();
    wxFileName cfgFile = wxFileName(cfgFileName);

    if (!cfgFile.Exists()) {
        if (configName.length()) {
            wxFileName baseConfig = wxFileName(getConfigFileName(true));
            if (baseConfig.Exists()) {
                std::string baseConfigFileName = baseConfig.GetFullPath(wxPATH_NATIVE).ToStdString();
                std::cout << "Creating new configuration file '" << cfgFileName << "' by copying '" << baseConfigFileName << "'..";
                wxCopyFile(baseConfigFileName, cfgFileName);
                if (!cfgFile.Exists()) {
                    std::cout << "failed." << std::endl;
                    return true;
                }
                std::cout << "ok." << std::endl;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    if (cfgFile.IsFileReadable()) {
        std::cout << "Loading:: configuration file '" << cfgFileName << "'" << std::endl;

        cfg.LoadFromFileXML(cfgFileName);
    } else {
        std::cout << "Error loading:: configuration file '" << cfgFileName << "' is not readable!" << std::endl;
        return false;
    }

    if (cfg.rootNode()->hasAnother("window")) {
        int x,y,w,h;
        int max;
        
        DataNode *win_node = cfg.rootNode()->getNext("window");
        
        if (win_node->hasAnother("w") && win_node->hasAnother("h") && win_node->hasAnother("x") && win_node->hasAnother("y")) {
            win_node->getNext("x")->element()->get(x);
            win_node->getNext("y")->element()->get(y);
            win_node->getNext("w")->element()->get(w);
            win_node->getNext("h")->element()->get(h);
            
            winX.store(x);
            winY.store(y);
            winW.store(w);
            winH.store(h);
        }
        
        if (win_node->hasAnother("max")) {
            win_node->getNext("max")->element()->get(max);
            winMax.store(max?true:false);
        }

        if (win_node->hasAnother("theme")) {
            int theme;
            win_node->getNext("theme")->element()->get(theme);
            themeId.store(theme);
        }

        if (win_node->hasAnother("snap")) {
			long long snapVal;
			win_node->getNext("snap")->element()->get(snapVal);
			snap.store(snapVal);
		}

        if (win_node->hasAnother("center_freq")) {
            long long freqVal;
            win_node->getNext("center_freq")->element()->get(freqVal);
            centerFreq.store(freqVal);
        }

        if (win_node->hasAnother("waterfall_lps")) {
            int lpsVal;
            win_node->getNext("waterfall_lps")->element()->get(lpsVal);
            waterfallLinesPerSec.store(lpsVal);
        }
        
        if (win_node->hasAnother("spectrum_avg")) {
            float avgVal;
            win_node->getNext("spectrum_avg")->element()->get(avgVal);
            spectrumAvgSpeed.store(avgVal);
        }
    }
    
    if (cfg.rootNode()->hasAnother("devices")) {
        DataNode *devices_node = cfg.rootNode()->getNext("devices");

        while (devices_node->hasAnother("device")) {
            DataNode *device_node = devices_node->getNext("device");
            if (device_node->hasAnother("id")) {
                std::string deviceId = device_node->getNext("id")->element()->toString();

                getDevice(deviceId)->load(device_node);
            }
        }
    }
    
    if (cfg.rootNode()->hasAnother("manual_devices")) {
        DataNode *manuals_node = cfg.rootNode()->getNext("manual_devices");
        
        while (manuals_node->hasAnother("device")) {
            DataNode *manual_node = manuals_node->getNext("device");
            if (manual_node->hasAnother("factory") && manual_node->hasAnother("params")) {
                SDRManualDef mdef;
                
                mdef.factory = manual_node->getNext("factory")->element()->toString();
                mdef.params = manual_node->getNext("params")->element()->toString();

                manualDevices.push_back(mdef);
            }
        }
    }
    
#ifdef USE_HAMLIB
    if (cfg.rootNode()->hasAnother("rig")) {
        DataNode *rig_node = cfg.rootNode()->getNext("rig");

        if (rig_node->hasAnother("model")) {
            int loadModel;
            rig_node->getNext("model")->element()->get(loadModel);
            rigModel.store(loadModel?loadModel:1);
        }
        if (rig_node->hasAnother("rate")) {
            int loadRate;
            rig_node->getNext("rate")->element()->get(loadRate);
            rigRate.store(loadRate?loadRate:57600);
        }
        if (rig_node->hasAnother("port")) {
            rigPort = rig_node->getNext("port")->element()->toString();
        }
    }
#endif


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

  
  if (argc!=2) {
    std::cout << "Usage: ./endpointGain.exe [octet]\n";
    //std::cout << "The code will produce comparisons for every octet in the range given,\non an octet-by-octet basis, and as a whole, using the Super-Sum\n";
    exit(0);
  }
  

  int octet = atoi(argv[1]);

  if ( std::find(badOct.begin(), badOct.end(),octet) != badOct.end() ) {

    std::cout << "Bad Octet... \n";

    std::ofstream gainFile(TString::Format("%s/EndpointGain/endpointGain_octet-%i.dat", getenv("ENDPOINT_ANALYSIS"),octet));

    for ( int i=0; i<8; ++i )  gainFile << 1. << std::endl;

    gainFile.close();

    return 0;
  }
  

  int nBins = 100;
  double minRange = 0.;
  double maxRange = 1000.;
  
  std::vector <int> runs = readOctetFile(octet);
  std::vector <int> bgruns = readOctetFileForBGruns(octet);

  std::vector < std::vector <Double_t> > pmtBackgroundRates = readPMTbackgroundRates(octet);

  

  ////////////////// Begin with data files /////////////////////

  // Vectors for creating the individual runs events and errors
  std::vector < std::vector < std::vector <Double_t> > > pmtSpec;
  std::vector < std::vector < std::vector <Double_t> > > pmtSpecErr;
    
  pmtSpec.resize(runs.size(),std::vector<std::vector<Double_t>>(8,std::vector<Double_t>(nBins,0.)));
  pmtSpecErr.resize(runs.size(),std::vector<std::vector<Double_t>>(8,std::vector<Double_t>(nBins,0.)));

  std::vector < std::vector < std::vector <Double_t> > > bgpmtSpec;
  std::vector < std::vector < std::vector <Double_t> > > bgpmtSpecErr;
    
  bgpmtSpec.resize(runs.size(),std::vector<std::vector<Double_t>>(8,std::vector<Double_t>(nBins,0.)));
  bgpmtSpecErr.resize(runs.size(),std::vector<std::vector<Double_t>>(8,std::vector<Double_t>(nBins,0.)));

  // Now loop over each run to determine the individual spectra, then fill their appropriate bins in the vector

  TH1D *spec[8]; // All 8 PMTs signals
  TH1D *bgspec[8]; // All 8 PMTs bg signals
  TH1D *simspec[8]; // All 8 PMTs signals

  int nRun = 0;
  
  std::vector <Double_t> totalTime(runs.size(),0.); // Holds the runLengths 
  std::vector <Double_t> bgtotalTime(runs.size(),0.); // Holds the runLengths 
  
  //runs.resize(0);
  for ( auto rn : runs ) {

    for ( int i=0; i<8; ++i ) {
      spec[i] = new TH1D(TString::Format("PMT%i",i),TString::Format("PMT %i",i),
		      nBins, minRange, maxRange);
    }
    
    // DataTree structure
    DataTree t;

    // Input ntuple
    char tempIn[500];
    sprintf(tempIn, "%s/replay_pass3_%i.root", getenv("REPLAY_PASS3"),rn);
    
    t.setupInputTree(std::string(tempIn),"pass3");

    unsigned int nevents = t.getEntries();

    t.getEvent(nevents-1);
    totalTime[nRun] = t.Time;

    double r2E = 0.; //position of event squared
    double r2W = 0.;
    
    for (unsigned int n=0 ; n<nevents ; n++ ) {

      t.getEvent(n);

      r2E = t.xE.center*t.xE.center + t.yE.center*t.yE.center;
      r2W = t.xW.center*t.xW.center + t.yW.center*t.yW.center;

      if ( t.PID==1 && t.Side<2 && t.Type==0 && t.Erecon>0. ) {

	if ( t.Side==0 ) {
	  if ( t.xeRC>6 || t.yeRC>6 ) continue; //only look at MWPC signal on East
	  else if ( t.xE.mult<1 || t.yE.mult<1 ) continue;
	}
	else if ( t.Side==1 ) {
	  if ( t.xwRC>6 || t.ywRC>6 ) continue; //only look at MWPC signal on West
	  else if ( t.xW.mult<1 || t.yW.mult<1 ) continue;      
	}

	if ( r2E > 30.*30. || r2W > 30.*30. ) continue;

	if ( t.Side==0 ) {
	  spec[0]->Fill(t.ScintE_bare.e1);
	  spec[1]->Fill(t.ScintE_bare.e2);
	  spec[2]->Fill(t.ScintE_bare.e3);
	  spec[3]->Fill(t.ScintE_bare.e4);
	}

	if ( t.Side==1 ) {
	  spec[4]->Fill(t.ScintW_bare.e1);
	  spec[5]->Fill(t.ScintW_bare.e2);
	  spec[6]->Fill(t.ScintW_bare.e3);
	  spec[7]->Fill(t.ScintW_bare.e4);
	}

      }
    }

    for ( int p=0; p<8; ++p ) {
      for ( int bin=1; bin<=nBins; ++bin ) {
	pmtSpec[nRun][p][bin-1] = (double)spec[p]->GetBinContent(bin)/totalTime[nRun];
	pmtSpecErr[nRun][p][bin-1] = spec[p]->GetBinError(bin)/totalTime[nRun];
      }
    }

    for ( int i=0; i<8; ++i ) { 
      // std::cout << "deleting spec[" << i << "]\n";
      delete spec[i];
    }
    nRun++;
    
  }

  nRun = 0;

  for ( auto rn : bgruns ) {

    for ( int i=0; i<8; ++i ) {
      bgspec[i] = new TH1D(TString::Format("bgPMT%i",i),TString::Format("bg PMT %i",i),
		      nBins, minRange, maxRange);
    }
    
    // DataTree structure
    DataTree t;

    // Input ntuple
    char tempIn[500];
    sprintf(tempIn, "%s/replay_pass3_%i.root", getenv("REPLAY_PASS3"),rn);
    
    t.setupInputTree(std::string(tempIn),"pass3");

    unsigned int nevents = t.getEntries();

    t.getEvent(nevents-1);
    bgtotalTime[nRun] = t.Time;

    double r2E = 0.; //position of event squared
    double r2W = 0.;
    
    for (unsigned int n=0 ; n<nevents ; n++ ) {

      t.getEvent(n);

      r2E = t.xE.center*t.xE.center + t.yE.center*t.yE.center;
      r2W = t.xW.center*t.xW.center + t.yW.center*t.yW.center;

      if ( t.PID==1 && t.Side<2 && t.Type==0 && t.Erecon>0. ) {

	if ( t.Side==0 ) {
	  if ( t.xeRC>6 || t.yeRC>6 ) continue; //only look at MWPC signal on East
	  else if ( t.xE.mult<1 || t.yE.mult<1 ) continue;
	}
	else if ( t.Side==1 ) {
	  if ( t.xwRC>6 || t.ywRC>6 ) continue; //only look at MWPC signal on West
	  else if ( t.xW.mult<1 || t.yW.mult<1 ) continue;      
	}

	if ( r2E > 30.*30. || r2W > 30.*30. ) continue;

	if ( t.Side==0 ) {
	  bgspec[0]->Fill(t.ScintE_bare.e1);
	  bgspec[1]->Fill(t.ScintE_bare.e2);
	  bgspec[2]->Fill(t.ScintE_bare.e3);
	  bgspec[3]->Fill(t.ScintE_bare.e4);
	}

	if ( t.Side==1 ) {
	  bgspec[4]->Fill(t.ScintW_bare.e1);
	  bgspec[5]->Fill(t.ScintW_bare.e2);
	  bgspec[6]->Fill(t.ScintW_bare.e3);
	  bgspec[7]->Fill(t.ScintW_bare.e4);
	}

      }
    }
    std::cout << "Made it through filling hists\n";
    for ( int p=0; p<8; ++p ) {
      for ( int bin=1; bin<=nBins; ++bin ) {
	bgpmtSpec[nRun][p][bin-1] = (double)bgspec[p]->GetBinContent(bin)/bgtotalTime[nRun];
	bgpmtSpecErr[nRun][p][bin-1] = ( bgspec[p]->GetBinContent(bin)>20 ?
					 bgspec[p]->GetBinError(bin)/bgtotalTime[nRun] :
					 TMath::Sqrt(pmtBackgroundRates[bin-1][p]/bgtotalTime[nRun]) );
      }
    }

    for ( int i=0; i<8; ++i ) { 
      // std::cout << "deleting spec[" << i << "]\n";
      delete bgspec[i];
    }
    nRun++;
    
  }

  

  ////////////// Now for simulation //////////////////
  // Vectors for creating the individual runs events and errors
  std::vector < std::vector < std::vector <Double_t> > > simSpec;
  std::vector < std::vector < std::vector <Double_t> > > simSpecErr;
    
  simSpec.resize(runs.size(),std::vector<std::vector<Double_t>>(8,std::vector<Double_t>(nBins,0.)));
  simSpecErr.resize(runs.size(),std::vector<std::vector<Double_t>>(8,std::vector<Double_t>(nBins,0.)));

  

  // Now loop over each run to determine the individual spectra, then fill their appropriate bins in the vector

  nRun = 0;
  
  for ( auto rn : runs ) {

    for ( int i=0; i<8; ++i ) {
      simspec[i] = new TH1D(TString::Format("SIM%i",i),TString::Format("SIM %i",i),
			 nBins, minRange, maxRange);
    }
    
    TFile *f = new TFile(TString::Format("%s/beta/revCalSim_%i_Beta.root",getenv("REVCALSIM"),rn), "READ");
    TTree *Tin = (TTree*)f->Get("revCalSim");

    std::cout << "Reading from " << TString::Format("%s/beta_highStatistics/revCalSim_%i_Beta.root",getenv("REVCALSIM"),rn).Data() << "\n";
    
    Double_t e0,e1,e2,e3,e4,e5,e6,e7;
    MWPC xE, yE, xW, yW;
    int PID, Side, Type;
    Double_t Erecon;
    
    
    Tin->SetBranchAddress("PID", &PID);
    Tin->SetBranchAddress("type", &Type);
    Tin->SetBranchAddress("side", &Side); 
    Tin->SetBranchAddress("Erecon",&Erecon);
    Tin->SetBranchAddress("xE",&xE);
    Tin->SetBranchAddress("yE",&yE);
    Tin->SetBranchAddress("xW",&xW);
    Tin->SetBranchAddress("yW",&yW);
    Tin->GetBranch("PMT")->GetLeaf("Evis0")->SetAddress(&e0);
    Tin->GetBranch("PMT")->GetLeaf("Evis1")->SetAddress(&e1);
    Tin->GetBranch("PMT")->GetLeaf("Evis2")->SetAddress(&e2);
    Tin->GetBranch("PMT")->GetLeaf("Evis3")->SetAddress(&e3);
    Tin->GetBranch("PMT")->GetLeaf("Evis4")->SetAddress(&e4);
    Tin->GetBranch("PMT")->GetLeaf("Evis5")->SetAddress(&e5);
    Tin->GetBranch("PMT")->GetLeaf("Evis6")->SetAddress(&e6);
    Tin->GetBranch("PMT")->GetLeaf("Evis7")->SetAddress(&e7);
    /*
      Tin->GetBranch("xE")->GetLeaf("center")->SetAddress(&EmwpcX);
      Tin->GetBranch("yE")->GetLeaf("center")->SetAddress(&EmwpcY);
      Tin->GetBranch("xW")->GetLeaf("center")->SetAddress(&WmwpcX);
      Tin->GetBranch("yW")->GetLeaf("center")->SetAddress(&WmwpcY);
      Tin->GetBranch("xE")->GetLeaf("nClipped")->SetAddress(&xE_nClipped);
      Tin->GetBranch("yE")->GetLeaf("nClipped")->SetAddress(&yE_nClipped);
      Tin->GetBranch("xW")->GetLeaf("nClipped")->SetAddress(&xW_nClipped);
      Tin->GetBranch("yW")->GetLeaf("nClipped")->SetAddress(&yW_nClipped);
      Tin->GetBranch("xE")->GetLeaf("mult")->SetAddress(&xE_mult);
      Tin->GetBranch("yE")->GetLeaf("mult")->SetAddress(&yE_mult);
      Tin->GetBranch("xW")->GetLeaf("mult")->SetAddress(&xW_mult);
      Tin->GetBranch("yW")->GetLeaf("mult")->SetAddress(&yW_mult);*/
    
    
    double r2E = 0.; //position of event squared
    double r2W = 0.;

    UInt_t nevents = Tin->GetEntriesFast();
    
    for (unsigned int n=0 ; n<nevents ; n++ ) {
      
      Tin->GetEvent(n);
      
      r2E = xE.center*xE.center + yE.center*yE.center;
      r2W = xW.center*xW.center + yW.center*yW.center;

      if ( PID==1 && Side<2 && Type==0 && Erecon>0. ) {

	if ( Side==0 && ( xE.mult<1 || yE.mult<1 ) ) continue;
	else if ( Side==1 && ( xW.mult<1 || yW.mult<1 ) ) continue;

	if ( r2E > 30.*30. || r2W > 30.*30. ) continue;

	
	if ( Side==0 ) {
	  simspec[0]->Fill(e0);
	  simspec[1]->Fill(e1);
	  simspec[2]->Fill(e2);
	  simspec[3]->Fill(e3);
	}

	if ( Side==1 ) {
	  simspec[4]->Fill(e4);
	  simspec[5]->Fill(e5);
	  simspec[6]->Fill(e6);
	  simspec[7]->Fill(e7);
	}

      }
    }

    for ( int p=0; p<8; ++p ) {
      for ( int bin=1; bin<=nBins; ++bin ) {
	simSpec[nRun][p][bin-1] = (double)simspec[p]->GetBinContent(bin)/totalTime[nRun];
	simSpecErr[nRun][p][bin-1] = simspec[p]->GetBinError(bin)/totalTime[nRun];
      }
    }

    for ( int i=0; i<8; ++i ) { 
      // std::cout << "deleting spec[" << i << "]\n";
      delete simspec[i];
    }
    nRun++;
    delete f;
    
  }

  //Now we take the weighted average over the runs in the octet
  
  TFile *fout = new TFile(TString::Format("%s/EndpointGain/endpointGain_octet-%i.root",
					  getenv("ENDPOINT_ANALYSIS"),octet),"RECREATE");
  //TFile *fout = new TFile(TString::Format("endpointGain_octet-%i.root",
  //					  octet),"RECREATE");
  
  std::cout << "Made output rootfile...\n\n";

  // Data //

  for ( int i=0; i<8; ++i ) {

    spec[i] = new TH1D(TString::Format("PMT%i",i),TString::Format("PMT %i",i),
		    nBins, minRange, maxRange);

  }
 
  for ( int p=0; p<8; ++p ) {
    for ( int bin=1; bin<=nBins; ++bin ) {
      
      double numer = 0.;
      double denom = 0.;
      
      for ( UInt_t i=0; i<runs.size(); ++i ) {
	
	//First background subtract each rate (keeping the error on the rate as just the counting
	// error
	if (i==0) std::cout << bin << ": " <<  pmtSpec[i][p][bin-1] << " - " << bgpmtSpec[i][p][bin-1] << " = ";
	pmtSpec[i][p][bin-1] -= bgpmtSpec[i][p][bin-1];//pmtBackgroundRates[bin-1][p];	
	pmtSpecErr[i][p][bin-1] = TMath::Sqrt( 
					      TMath::Power(bgpmtSpecErr[i][p][bin-1],2) + 
					      TMath::Power(pmtSpecErr[i][p][bin-1],2) );
	if (i==0) std::cout << pmtSpec[i][p][bin-1] << std::endl;

	double weight = pmtSpecErr[i][p][bin-1]>0. ? 1./(pmtSpecErr[i][p][bin-1]*pmtSpecErr[i][p][bin-1]) : 0.;
	numer += pmtSpec[i][p][bin-1]*weight;
	denom += weight;
      }

      spec[p]->SetBinContent(bin, denom>0. ? numer/denom : 0.);
      spec[p]->SetBinError(bin, denom>0. ? TMath::Sqrt(1./denom) : 0. );
    }
  }

  // Sim //
  for ( int i=0; i<8; ++i ) {

    simspec[i] = new TH1D(TString::Format("SIM%i",i),TString::Format("SIM %i",i),
		    nBins, minRange, maxRange);

  }
 
  for ( int p=0; p<8; ++p ) {
    for ( int bin=1; bin<=nBins; ++bin ) {

      double numer = 0.;
      double denom = 0.;
      
      for ( UInt_t i=0; i<runs.size(); ++i ) {
	double weight = simSpec[i][p][bin-1]>0. ? 1./(simSpecErr[i][p][bin-1]*simSpecErr[i][p][bin-1]) : 0.;
	numer += simSpec[i][p][bin-1]*weight;
	denom += weight;
      }

      simspec[p]->SetBinContent(bin, denom>0. ? numer/denom : 0.);
      simspec[p]->SetBinError(bin, denom>0. ? TMath::Sqrt(1./denom) : 0. );
    }
  }

  
  
  
  /////////////////////////// Kurie Fitting ////////////////////

  // First I'm going to Kurie fit the simulated endpoint, and then
  // I will iterate until the data until the endpoint matches this endpoint

  std::vector <Double_t> gain(8,0.);

  TGraphErrors kurie[8];
  TGraphErrors simkurie[8];

  KurieFitter kf, simkf;

  for ( int i=0; i<8; ++i ) {
    
    simkf.FitSpectrum(simspec[i],250.,500.,1.); //Fit the simulated spectrum to get relative endpoint

    kf.setActualW0( simkf.returnW0() ); // Setting the comparison endpoint to the extracted ep from sim
    kf.IterativeKurie(spec[i],250.,500.,1.,1.e-7);
   

    kurie[i] = kf.returnKuriePlot();
    kurie[i].SetName(TString::Format("data%i",i));
    kurie[i].Write();
    
    simkurie[i] = simkf.returnKuriePlot();
    simkurie[i].SetName(TString::Format("sim%i",i));
    simkurie[i].Write();

    gain[i] = kf.returnAlpha();

  }

  
  /*///// Getting the gains... 

  std::vector <Double_t> alpha_data(8,0.);
  std::vector <Double_t> alpha_sim(8,0.);
  std::vector <Double_t> gain(8,0.);

  TGraphErrors kurie[8];
  TGraphErrors simkurie[8];

  KurieFitter kf, simkf;

  for ( int i=0; i<8; ++i ) {
    
    kf.IterativeKurie(spec[i],300.,500.,1.1,1.e-6);
    simkf.IterativeKurie(simspec[i],300.,500.,1.1,1.e-6);

    kurie[i] = kf.returnKuriePlot();
    kurie[i].SetName(TString::Format("data%i",i));
    kurie[i].Write();
    
    simkurie[i] = simkf.returnKuriePlot();
    simkurie[i].SetName(TString::Format("sim%i",i));
    simkurie[i].Write();

    alpha_data[i] = kf.returnAlpha();
    alpha_sim[i] = simkf.returnAlpha();

    gain[i] = alpha_sim[i]>0. ? alpha_data[i]/alpha_sim[i] : 1.;

    }*/

  /// Write out pmt endpoint gain corrections
  std::ofstream gainFile(TString::Format("%s/EndpointGain/endpointGain_octet-%i.dat",
  					 getenv("ENDPOINT_ANALYSIS"),octet));
  // std::ofstream gainFile(TString::Format("endpointGain_octet-%i.dat",octet));

  for ( auto g : gain ) gainFile << g << std::endl;

  gainFile.close();
  

  fout->Write();
  delete fout;

  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);
  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;
}
Exemple #17
0
bool AppFrame::loadSession(std::string fileName) {
    DataTree l;
    if (!l.LoadFromFileXML(fileName)) {
        return false;
    }

    wxGetApp().getDemodMgr().terminateAll();

    try {
        DataNode *header = l.rootNode()->getNext("header");

        std::string version(*header->getNext("version"));
        long long center_freq = *header->getNext("center_freq");

        std::cout << "Loading " << version << " session file" << std::endl;
        std::cout << "\tCenter Frequency: " << center_freq << std::endl;

        wxGetApp().setFrequency(center_freq);

        DataNode *demodulators = l.rootNode()->getNext("demodulators");

        while (demodulators->hasAnother("demodulator")) {
            DataNode *demod = demodulators->getNext("demodulator");

            if (!demod->hasAnother("bandwidth") || !demod->hasAnother("frequency")) {
                continue;
            }

            long bandwidth = *demod->getNext("bandwidth");
            long long freq = *demod->getNext("frequency");
            int type = demod->hasAnother("type") ? *demod->getNext("type") : DEMOD_TYPE_FM;
            float squelch_level = demod->hasAnother("squelch_level") ? (float) *demod->getNext("squelch_level") : 0;
            int squelch_enabled = demod->hasAnother("squelch_enabled") ? (int) *demod->getNext("squelch_enabled") : 0;
            int stereo = demod->hasAnother("stereo") ? (int) *demod->getNext("stereo") : 0;
            std::string output_device = demod->hasAnother("output_device") ? string(*(demod->getNext("output_device"))) : "";
            float gain = demod->hasAnother("gain") ? (float) *demod->getNext("gain") : 1.0;

            DemodulatorInstance *newDemod = wxGetApp().getDemodMgr().newThread();
            newDemod->setDemodulatorType(type);
            newDemod->setBandwidth(bandwidth);
            newDemod->setFrequency(freq);
            newDemod->setGain(gain);
            newDemod->updateLabel(freq);
            if (squelch_enabled) {
                newDemod->setSquelchEnabled(true);
                newDemod->setSquelchLevel(squelch_level);
            }
            if (stereo) {
                newDemod->setStereo(true);
            }

            bool found_device = false;
            std::map<int, RtAudio::DeviceInfo>::iterator i;
            for (i = outputDevices.begin(); i != outputDevices.end(); i++) {
                if (i->second.name == output_device) {
                    newDemod->setOutputDevice(i->first);
                    found_device = true;
                }
            }

            if (!found_device) {
                std::cout << "\tWarning: named output device '" << output_device << "' was not found. Using default output.";
            }

            newDemod->run();
            newDemod->setActive(false);
            wxGetApp().bindDemodulator(newDemod);

            std::cout << "\tAdded demodulator at frequency " << freq << " type " << type << std::endl;
            std::cout << "\t\tBandwidth: " << bandwidth << std::endl;
            std::cout << "\t\tSquelch Level: " << squelch_level << std::endl;
            std::cout << "\t\tSquelch Enabled: " << (squelch_enabled ? "true" : "false") << std::endl;
            std::cout << "\t\tStereo: " << (stereo ? "true" : "false") << std::endl;
            std::cout << "\t\tOutput Device: " << output_device << std::endl;
        }
    } catch (DataInvalidChildException &e) {
        std::cout << e.what() << std::endl;
        return false;
    } catch (DataTypeMismatchException &e) {
        std::cout << e.what() << std::endl;
        return false;
    }

    currentSessionFile = fileName;

    std::string filePart = fileName.substr(fileName.find_last_of(filePathSeparator) + 1);

    GetStatusBar()->SetStatusText(wxString::Format(wxT("Loaded session file: %s"), currentSessionFile.c_str()));
    SetTitle(wxString::Format(wxT("%s: %s"), CUBICSDR_TITLE, filePart.c_str()));

    return true;
}
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;
}
Exemple #19
0
DataTree Payment::generateDataTree() const
{
	DataTree result;
	result.set("id", asString(_data.id));
	result.set("pay_engine", asString(_data.pay_engine));
	result.set("provider_id", asString(_data.provider_id));
	result.set("data", _data.data);
	result.set("stamp", _data.stamp);
	result.set("bill_num", _data.bill_num);
	result.set("terminal_id", asString(_data.terminal_id));
	result.set("summ", asString(_data.summ));
	result.set("back_summ", asString(_data.back_summ));
	result.set("currency", asString(_data.currency));
	result.set("lo_perc", asString(_data.lo_perc));
	result.set("op_perc", asString(_data.op_perc));
	result.set("paysys_codename", asString(_data.paysys_codename));
	result.set("test", asString(_data.test));
	result.set("exists_int_checkreqs", asString(_data.exists_int_checkreqs));
	return result;
}
Exemple #20
0
bool AppConfig::load() {
    DataTree cfg;
    std::string cfgFileDir = getConfigDir();

    std::string cfgFileName = getConfigFileName();
    wxFileName cfgFile = wxFileName(cfgFileName);

    if (!cfgFile.Exists()) {
        if (configName.length()) {
            wxFileName baseConfig = wxFileName(getConfigFileName(true));
            if (baseConfig.Exists()) {
                std::string baseConfigFileName = baseConfig.GetFullPath(wxPATH_NATIVE).ToStdString();
                std::cout << "Creating new configuration file '" << cfgFileName << "' by copying '" << baseConfigFileName << "'..";
                wxCopyFile(baseConfigFileName, cfgFileName);
                if (!cfgFile.Exists()) {
                    std::cout << "failed." << std::endl;
                    return true;
                }
                std::cout << "ok." << std::endl;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    if (cfgFile.IsFileReadable()) {
        std::cout << "Loading:: configuration file '" << cfgFileName << "'" << std::endl;

        cfg.LoadFromFileXML(cfgFileName);
    } else {
        std::cout << "Error loading:: configuration file '" << cfgFileName << "' is not readable!" << std::endl;
        return false;
    }

    if (cfg.rootNode()->hasAnother("window")) {
        int x = 0 ,y = 0 ,w = 0 ,h = 0;
        int max = 0 ,tips = 0 ,perf_mode = 0 ,mpc = 0;
        
        DataNode *win_node = cfg.rootNode()->getNext("window");
        
        if (win_node->hasAnother("w") && win_node->hasAnother("h") && win_node->hasAnother("x") && win_node->hasAnother("y")) {

            win_node->getNext("x")->element()->get(x);
            win_node->getNext("y")->element()->get(y);
            win_node->getNext("w")->element()->get(w);
            win_node->getNext("h")->element()->get(h);
            
            winX.store(x);
            winY.store(y);
            winW.store(w);
            winH.store(h);
        }
        
        if (win_node->hasAnother("max")) {
            win_node->getNext("max")->element()->get(max);
            winMax.store(max?true:false);
        }

        if (win_node->hasAnother("tips")) {
            win_node->getNext("tips")->element()->get(tips);
            showTips.store(tips?true:false);
        }

        // default:
        perfMode.store(PERF_NORMAL);

        if (win_node->hasAnother("perf_mode")) {
            win_node->getNext("perf_mode")->element()->get(perf_mode);

            if (perf_mode == (int)PERF_LOW) {
                perfMode.store(PERF_LOW);
            } else if (perf_mode == (int)PERF_HIGH) {
                perfMode.store(PERF_HIGH);
            }
        }
       
        if (win_node->hasAnother("theme")) {
            int theme;
            win_node->getNext("theme")->element()->get(theme);
            themeId.store(theme);
        }

        if (win_node->hasAnother("font_scale")) {
            int fscale;
            win_node->getNext("font_scale")->element()->get(fscale);
            fontScale.store(fscale);
        }

        if (win_node->hasAnother("snap")) {
			long long snapVal;
			win_node->getNext("snap")->element()->get(snapVal);
			snap.store(snapVal);
		}

        if (win_node->hasAnother("center_freq")) {
            long long freqVal;
            win_node->getNext("center_freq")->element()->get(freqVal);
            centerFreq.store(freqVal);
        }

        if (win_node->hasAnother("waterfall_lps")) {
            int lpsVal;
            win_node->getNext("waterfall_lps")->element()->get(lpsVal);
            waterfallLinesPerSec.store(lpsVal);
        }
        
        if (win_node->hasAnother("spectrum_avg")) {
            float avgVal;
            win_node->getNext("spectrum_avg")->element()->get(avgVal);
            spectrumAvgSpeed.store(avgVal);
        }

        if (win_node->hasAnother("modemprops_collapsed")) {
            win_node->getNext("modemprops_collapsed")->element()->get(mpc);
            modemPropsCollapsed.store(mpc?true:false);
        }
        
        if (win_node->hasAnother("db_offset")) {
            DataNode *offset_node = win_node->getNext("db_offset");
            int offsetValue = 0;
            offset_node->element()->get(offsetValue);
            setDBOffset(offsetValue);
        }

        if (win_node->hasAnother("main_split")) {
            float gVal;
            win_node->getNext("main_split")->element()->get(gVal);
            mainSplit.store(gVal);
        }
        
        if (win_node->hasAnother("vis_split")) {
            float gVal;
            win_node->getNext("vis_split")->element()->get(gVal);
            visSplit.store(gVal);
        }
        
        if (win_node->hasAnother("bookmark_split")) {
            float gVal;
            win_node->getNext("bookmark_split")->element()->get(gVal);
            bookmarkSplit.store(gVal);
        }

        if (win_node->hasAnother("bookmark_visible")) {
            int bVal;
            win_node->getNext("bookmark_visible")->element()->get(bVal);
            bookmarksVisible.store(bVal);
        }
    }
    
	//Recording settings:
    if (cfg.rootNode()->hasAnother("recording")) {
        DataNode *rec_node = cfg.rootNode()->getNext("recording");

        if (rec_node->hasAnother("path")) {
            DataNode *rec_path = rec_node->getNext("path");
            recordingPath = rec_path->element()->toString();
        }

		if (rec_node->hasAnother("squelch")) {
			DataNode *rec_squelch = rec_node->getNext("squelch");
			rec_squelch->element()->get(recordingSquelchOption);
		}

		if (rec_node->hasAnother("file_time_limit")) {
			DataNode *rec_file_time_limit = rec_node->getNext("file_time_limit");
			rec_file_time_limit->element()->get(recordingFileTimeLimitSeconds);
		}
    }
    
    if (cfg.rootNode()->hasAnother("devices")) {
        DataNode *devices_node = cfg.rootNode()->getNext("devices");

        while (devices_node->hasAnother("device")) {
            DataNode *device_node = devices_node->getNext("device");
            if (device_node->hasAnother("id")) {
                std::string deviceId = device_node->getNext("id")->element()->toString();

                getDevice(deviceId)->load(device_node);
            }
        }
    }
    
    if (cfg.rootNode()->hasAnother("manual_devices")) {
        DataNode *manuals_node = cfg.rootNode()->getNext("manual_devices");
        
        while (manuals_node->hasAnother("device")) {
            DataNode *manual_node = manuals_node->getNext("device");
            if (manual_node->hasAnother("factory") && manual_node->hasAnother("params")) {
                SDRManualDef mdef;
                
                mdef.factory = manual_node->getNext("factory")->element()->toString();
                mdef.params = manual_node->getNext("params")->element()->toString();

                manualDevices.push_back(mdef);
            }
        }
    }
    
#ifdef USE_HAMLIB
    if (cfg.rootNode()->hasAnother("rig")) {
        DataNode *rig_node = cfg.rootNode()->getNext("rig");

        if (rig_node->hasAnother("enabled")) {
            int loadEnabled;
            rig_node->getNext("enabled")->element()->get(loadEnabled);
            rigEnabled.store(loadEnabled?true:false);
        }
        if (rig_node->hasAnother("model")) {
            int loadModel;
            rig_node->getNext("model")->element()->get(loadModel);
            rigModel.store(loadModel?loadModel:1);
        }
        if (rig_node->hasAnother("rate")) {
            int loadRate;
            rig_node->getNext("rate")->element()->get(loadRate);
            rigRate.store(loadRate?loadRate:57600);
        }
        if (rig_node->hasAnother("port")) {
            rigPort = rig_node->getNext("port")->element()->toString();
        }
        if (rig_node->hasAnother("control")) {
            int loadControl;
            rig_node->getNext("control")->element()->get(loadControl);
            rigControlMode.store(loadControl?true:false);
        }
        if (rig_node->hasAnother("follow")) {
            int loadFollow;
            rig_node->getNext("follow")->element()->get(loadFollow);
            rigFollowMode.store(loadFollow?true:false);
        }
        if (rig_node->hasAnother("center_lock")) {
            int loadCenterLock;
            rig_node->getNext("center_lock")->element()->get(loadCenterLock);
            rigCenterLock.store(loadCenterLock?true:false);
        }
        if (rig_node->hasAnother("follow_modem")) {
            int loadFollow;
            rig_node->getNext("follow_modem")->element()->get(loadFollow);
            rigFollowModem.store(loadFollow?true:false);
        }
    }
#endif


    return true;
}
Exemple #21
0
bool AppConfig::load() {
    DataTree cfg;
    std::string cfgFileDir = getConfigDir();

    std::string cfgFileName = getConfigFileName();
    wxFileName cfgFile = wxFileName(cfgFileName);

    if (!cfgFile.Exists()) {
        if (configName.length()) {
            wxFileName baseConfig = wxFileName(getConfigFileName(true));
            if (baseConfig.Exists()) {
                std::string baseConfigFileName = baseConfig.GetFullPath(wxPATH_NATIVE).ToStdString();
                std::cout << "Creating new configuration file '" << cfgFileName << "' by copying '" << baseConfigFileName << "'..";
                wxCopyFile(baseConfigFileName, cfgFileName);
                if (!cfgFile.Exists()) {
                    std::cout << "failed." << std::endl;
                    return true;
                }
                std::cout << "ok." << std::endl;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    if (cfgFile.IsFileReadable()) {
        std::cout << "Loading:: configuration file '" << cfgFileName << "'" << std::endl;

        cfg.LoadFromFileXML(cfgFileName);
    } else {
        std::cout << "Error loading:: configuration file '" << cfgFileName << "' is not readable!" << std::endl;
        return false;
    }

    if (cfg.rootNode()->hasAnother("window")) {
        int x,y,w,h;
        int max;

        DataNode *win_node = cfg.rootNode()->getNext("window");

        if (win_node->hasAnother("w") && win_node->hasAnother("h") && win_node->hasAnother("x") && win_node->hasAnother("y")) {
            win_node->getNext("x")->element()->get(x);
            win_node->getNext("y")->element()->get(y);
            win_node->getNext("w")->element()->get(w);
            win_node->getNext("h")->element()->get(h);

            winX.store(x);
            winY.store(y);
            winW.store(w);
            winH.store(h);
        }

        if (win_node->hasAnother("max")) {
            win_node->getNext("max")->element()->get(max);
            winMax.store(max?true:false);
        }

        if (win_node->hasAnother("theme")) {
            int theme;
            win_node->getNext("theme")->element()->get(theme);
            themeId.store(theme);
        }

        if (win_node->hasAnother("snap")) {
            long long snapVal;
            win_node->getNext("snap")->element()->get(snapVal);
            snap.store(snapVal);
        }

        if (win_node->hasAnother("center_freq")) {
            long long freqVal;
            win_node->getNext("center_freq")->element()->get(freqVal);
            centerFreq.store(freqVal);
        }
    }

    if (cfg.rootNode()->hasAnother("devices")) {
        DataNode *devices_node = cfg.rootNode()->getNext("devices");

        while (devices_node->hasAnother("device")) {
            DataNode *device_node = devices_node->getNext("device");
            if (device_node->hasAnother("id")) {
                std::string deviceId;
                device_node->getNext("id")->element()->get(deviceId);

                getDevice(deviceId)->load(device_node);
            }
        }
    }

    return true;
}
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;
}