#!/usr/bin/env Rscript

random.result.files <- c("~/research/security_games/experiments-new/graph-random/out/mean.csv",
                         "~/research/security_games/experiments-new/graph6-random/out/mean.csv",
                         "~/research/security_games/experiments-new/graph7-random/out/mean.csv",
                         "~/research/security_games/experiments-new/superdiv-uniform/out/mean.csv"
                         )


read.results.file <- function (file) {
    read.csv(file, header=TRUE)[, c("game", "defender.payoff", "trainingTime", "method")]
}

random.results <- do.call(rbind,Map(read.results.file, random.result.files))

result.comparison <- function (baseline.file, others.file) {
    baseline.results <- read.results.file(baseline.file)
    other.results <- Map(read.results.file, others.file)

    process.other.result <- function(other.result) {
        results <- merge(merge(baseline.results, other.result, suffixes = c("", ".other"), by = "game"), random.results, by = "game", suffixes = c("", ".random"))

        data.frame(game=results$game, time.base=results$trainingTime,
                   time.factor=results$trainingTime.other/results$trainingTime,
                   score.relative = (results$defender.payoff.other-results$defender.payoff.random)/
                       (results$defender.payoff - results$defender.payoff.random),
                   defender.diff = results$defender.payoff - results$defender.payoff.other
                   )
    }

    processed.results <- Map(process.other.result, other.results)
    output.files <- Map(function(input.file){paste0(basename(gsub("/out/mean.csv", "", input.file)), ".csv")}, others.file)
    Map(function(df, file) {write.csv(df, file, row.names = FALSE)}, processed.results, output.files)
}

# https://stackoverflow.com/questions/13858262/how-to-split-a-vector-by-delimiter
split.vec <- function(vec, sep) {
    is.sep <- vec == sep
    split(vec[!is.sep], cumsum(is.sep)[!is.sep])
}

sets.to.process <- split.vec(commandArgs(trailingOnly = TRUE), "X")

Map(function (set) {result.comparison(set[1], set[-1])}, sets.to.process)
