require('zoo')
require('plotrix')
require('ggplot2')

aggregation.lengths <- c(1,50,100,500,1000)
plot.driver <- "png"

generate.max.agg.plots <- function (run.data.list, joined.plot.name, agg.window, output.dir=".") {
    
    for(name in names(run.data.list)) {
        print(paste(joined.plot.name,name))
        do.call(plot.driver, list(paste(output.dir,paste(joined.plot.name,name,"run",agg.window,plot.driver,sep="."), sep="/")))
        twoord.plot(run.data.list[[name]]$iteration, run.data.list[[name]]$dr, run.data.list[[name]]$iteration, run.data.list[[name]]$ah.len, main=paste(joined.plot.name, name, sep="."), ylab="Defender reward", rylab="Attacker history len", type=c("l","l"))
        dev.off()

        do.call(plot.driver, list(paste(output.dir,paste(joined.plot.name,name,"runar",agg.window,plot.driver,sep="."), sep="/")))
        twoord.plot(run.data.list[[name]]$iteration, run.data.list[[name]]$dr, run.data.list[[name]]$iteration, run.data.list[[name]]$ar, main=paste(joined.plot.name, name, sep="."), ylab="Defender payoff", rylab="Attacker payoff", type=c("l","l"))
        dev.off()
    }

    do.call(plot.driver, list(paste(output.dir, paste(joined.plot.name,"joined","run",agg.window,plot.driver,sep="."), sep="/")))
    print(Reduce(function(a,b) a+b[[1]],
           Map(function(name) {list(
               geom_path(data=as.data.frame(run.data.list[[name]]), aes(x=iteration, y=dr, color=ah.len)))

           },names(run.data.list))
          ,ggplot())+scale_colour_gradientn(colours=c("#0000FFFF","#00FF00FF", "#FF0000FF"), trans="log"))
    dev.off()
}

ggplot.many.runs <- function (run.list) {
    print(
        Reduce(function(a,b) a+b,
               Map(function(el) {geom_path(data=el,
                                             aes(x=iteration, y=dr, color=ah.len))
               },run.list)
              ,ggplot())+scale_colour_gradientn(colours=c("#0000FFFF","#00FF00FF", "#FF0000FF"), trans="log")
    )
}

read.single.run <- function(file.prefix, file.number) {
    ah.file <- paste0(file.prefix,".",file.number,".ah.log")
    dr.file <- paste0(file.prefix,".",file.number,".dr.log")

    merge(read.table(dr.file, sep=" ", col.names=c("grabage", "iteration", "dr", "ar"))[,c(2,3,4)],
          read.table(ah.file, sep=" ", col.names=c("iteration", "ah.len")))
}

read.data.for.prefix <- function(file.prefix) {
    repeat.files <- list.files(pattern = paste0(file.prefix,"\\..*\\.dr\\.log$"))    
    file.numbers <- gsub(x=gsub(pattern=paste0("^",file.prefix,"."), replacement="", x=repeat.files), replacement="", pattern=".dr.log$")

    ah.files=paste0(file.prefix,".",file.numbers,".ah.log")


    Map(function(file.number) read.single.run(file.prefix, file.number), file.numbers)
}

iter.aggregation.single <- function(df, len) {
    df$dr <- rollapply(df$dr, FUN=max, width=len, partial=TRUE, align="r")
    df
}

iter.aggregation <- function(data, len) {
    Map(function(m) Map(function(df) iter.aggregation.single(df,len), m), data)
}

make.stat.row <- function(data) {
    data.frame(iterations=max(data$iteration), result=max(data$dr), max.ah.len=max(data$ah.len))
}

generate.plots <- function (super.joined.prefix, file.prefixes) {
    data <- Map(read.data.for.prefix, file.prefixes)
    names(data) <- file.prefixes
    
    for(l in aggregation.lengths) {
        agg.data <- iter.aggregation(data, l)
        for(file.prefix in file.prefixes) {
            generate.max.agg.plots(agg.data[[file.prefix]], file.prefix, l, "plots")
        }
        do.call(plot.driver, list(paste0("plots/",super.joined.prefix,".",l,".", plot.driver)))
        ggplot.many.runs(do.call(c, agg.data))
        dev.off()
    }

    transform.repeats <- function(prefix.data) {
        do.call(rbind, Map(make.stat.row, prefix.data))
    }

    transform.repeats.avg <- function(prefix.data) {
        data.frame(Map(mean, (do.call(rbind, Map(make.stat.row, prefix.data)))))
    }

    
    write.csv(do.call(rbind, Map(function(fp) cbind(config=fp, transform.repeats(data[[fp]])), file.prefixes)), paste0("plots/",paste(super.joined.prefix,"csv", sep=".")), row.names = FALSE)
    write.csv(do.call(rbind, Map(function(fp) cbind(config=fp, transform.repeats.avg(data[[fp]])), file.prefixes)), paste0("plots/",paste(super.joined.prefix,"avg","csv", sep=".")), row.names = FALSE)
}


generate.plots(commandArgs(trailingOnly = TRUE)[1], commandArgs(trailingOnly = TRUE)[-1])
        



warnings()


