#!/usr/bin/env Rscript

args <- commandArgs(trailingOnly = TRUE)

# Ensure at least one file is provided
if(length(args) < 1) {
  stop("Please provide at least one TSV file as input.")
}

# Read the first file to get the statistics names (assuming all files have the same structure)
first_file <- read.table(args[1], header = TRUE, sep="\t", stringsAsFactors = FALSE)
stats_names <- first_file$Statistics

# Initialize a data frame for results
results <- data.frame(Statistics = stats_names)

# Loop over all files and merge them into the results dataframe
for(file in args) {
  sample_data <- read.table(file, header = TRUE, sep="\t", stringsAsFactors = FALSE)
  sample_name <- colnames(sample_data)[2]
  results[sample_name] <- sample_data[,2]
}

# Print the results
write.table(results, sep="\t", quote=FALSE, row.names=FALSE, col.names=TRUE)

