#!/usr/bin/env Rscript

methods <- list(
    milp = "milp",
    momentum.l = "Mixed Tree momentum-long-fullexpand.json",
    momentum.long = "Mixed Tree momentum-longer-fullexpand.json",
    sign.coord.l = "Mixed Tree coordsign-long-fullexpand.json",
    sign.global.l = "Mixed Tree globalsign-long-fullexpand.json",
    momentum.s = "Mixed Tree momentum2.json",
    sign.coord.s = "Mixed Tree coordsign-std.json",
    global.coord.s = "Mixed Tree globalsign-std.json",
    bisect.s = "Mixed Tree bisect-std.json",
    bisect.fe = "Mixed Tree bisect-fullexpand.json"
)

file.list <- commandArgs(trailingOnly = TRUE)

read.inputs <- function(files) {
    do.call(rbind, Map(function(file) read.csv(file, header=TRUE)[,c("game", "defender.payoff", "method")], files))
}

data <- read.inputs(file.list)


filtered.methods <- Filter(function (x) x %in% data$method, methods)
unknown.methods <- as.list(setdiff(unique(data$method), filtered.methods))

shorten.name <- function(name) {
    name <- gsub("Mixed Tree ", "", name, fixed=TRUE)
    name <- gsub(".json", "", name, fixed=TRUE)
    name
}

names(unknown.methods) <- shorten.name(unknown.methods)

method.data <- Map(function(method) {
    mdata <- data[data$method==method, c("game", "defender.payoff")]
    mdata
}, c(filtered.methods, unknown.methods))

head(method.data)

for(name in names(method.data)) {
    names(method.data[[name]]) <- c("game", paste0(name,".defender.payoff"))
}

Map(head, method.data)

joint.data <- Reduce(function (df1, df2) merge(df1, df2, all.x=TRUE, all.y=TRUE), method.data[-1], method.data[[1]])

write.csv(joint.data, "cross-table.csv", row.names = FALSE)
