#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <cmath>
#include <TTree.h>
#include <TFile.h>
#include <filesystem>
namespace fs = std::filesystem;
using namespace std;
// Function to check if a value is valid (not NaN or Inf)
bool isValidValue(double value) {
return !isnan(value) && isfinite(value);
}
// Function to read CSV files from a folder
vector<string> listCSVFiles(const string& folderPath) {
vector<string> csvFiles;
if (!fs::exists(folderPath) || !fs::is_directory(folderPath)) {
cerr << "❌ Error: Directory not found - " << folderPath << endl;
return csvFiles;
}
for (const auto& entry : fs::directory_iterator(folderPath)) {
if (entry.is_regular_file() && entry.path().extension() == ".csv") {
csvFiles.push_back(entry.path().string());
}
}
sort(csvFiles.begin(), csvFiles.end()); // Ensuring consistent ordering
return csvFiles;
}
// Function to read CSV file dynamically
void readcsv(vector<double>& Time, vector<vector<double>>& Channels,
vector<string>& channelNames, const string& filename) {
ifstream file(filename);
if (!file.is_open()) {
cerr << "❌ Error: Could not open file: " << filename << endl;
return;
}
string line;
int numChannels = 0;
// Read the first valid data row's column headers
if (getline(file, line)) {
stringstream ss(line);
string column;
bool firstColumn = true;
while (getline(ss, column, ',')) {
if (firstColumn) {
firstColumn = false; // Skip the first column (time)
continue;
}
channelNames.push_back(column);
Channels.push_back(vector<double>()); // Initialize each channel vector
numChannels++;
}
}
// Read the waveform data
while (getline(file, line)) {
stringstream ss(line);
string value;
double t;
vector<double> channelValues;
// Read time value first
getline(ss, value, ',');
try {
t = stod(value);
} catch (...) {
cerr << "⚠️ Warning: Invalid time value found, skipping row." << endl;
continue;
}
int channelIndex = 0;
while (getline(ss, value, ',')) {
try {
double v = stod(value);
if (isValidValue(v) && channelIndex < numChannels) {
Channels[channelIndex].push_back(v);
}
} catch (...) {
cerr << "⚠️ Warning: Invalid value detected, skipping row." <<
endl;
}
channelIndex++;
}
Time.push_back(t);
}
file.close();
cout << "✅ File " << filename << " successfully processed with " << numChannels
<< " channels!" << endl;
}
// Function to process all CSV files in a folder
void processFolder(const string& folderPath) {
vector<string> csvFiles = listCSVFiles(folderPath);
if (csvFiles.empty()) {
cerr << "❌ No CSV files found in folder: " << folderPath << endl;
return;
}
for (const auto& file : csvFiles) {
vector<double> Time;
vector<vector<double>> Channels;
vector<string> channelNames;
readcsv(Time, Channels, channelNames, file);
}
}