library(Hmisc)

args = commandArgs(trailingOnly=TRUE)
if (length(args) < 4) {
  stop("At least four argument must be supplied (base path, mode, type, ref_type).", call.=FALSE)
}
projs <- c("antlr4", "junit", "MapDB", "mcMMO", "mct", "oryx", "titan")
metcounts = list()
for(projn in projs) {
    fname = paste0(args[1], projn, "/", projn, args[3], "_refactoring-diff.csv")
    mydata = read.csv(fname, sep = ",", dec=",", quote = "\"")
    LR=mydata[[args[4]]]==0
    print(fname)
    if (sum(LR)==length(LR))
        next
    pos = sum(LR)
    neg = length(LR) - pos
    #print(pos)
    #print(neg)
    for(i in names(mydata)) {
        if(startsWith(i, "Prev") && !endsWith(i, "Rules")) {
            pmet = i
            met = substr(i, 5, 100000)
            if (startsWith(met, "Warning")) {
                next
            }
            if (met == "NA") {
                met = paste0(met, ".")
            }
            dmet = paste0("Diff", met)
            ref = mydata[!LR, c(pmet,met)]
            noref = mydata[LR, c(pmet,met)]
            ref[[dmet]]<-ref[[met]]-ref[[pmet]]
            noref[[dmet]]<-noref[[met]]-noref[[pmet]]
            if (args[2] == "wilcox") {
                res = wilcox.test(mydata[[met]] ~ LR, data=mydata)
                if (!is.na(res["p.value"])) {
                    write.table(t(c(met, res["p.value"], ((2*res[["statistic"]])/(pos*neg)-1))), append = TRUE, col.names = FALSE, row.names = FALSE, sep = ";", quote = FALSE)
                    if (exists(met, where=metcounts)) {
                        metcounts[[met]] <- metcounts[[met]] + 1
                    } else {
                        metcounts[[met]] <- 1
                    }
                }
            } else if (args[2] == "wilcoxdiff") {
                res = wilcox.test(ref[[dmet]], noref[[dmet]])
                if (!is.na(res["p.value"])) {
                    write.table(t(c(met, res["p.value"], ((2*res[["statistic"]])/(pos*neg)-1))), append = TRUE, col.names = FALSE, row.names = FALSE, sep = ";", quote = FALSE)
                    if (exists(met, where=metcounts)) {
                        metcounts[[met]] <- metcounts[[met]] + 1
                    } else {
                        metcounts[[met]] <- 1
                    }
                }
            } else if (args[2] == "avg") {
                write.table(t(c(met, mean(ref[[pmet]]), mean(ref[[met]]), mean(ref[[dmet]]), mean(noref[[pmet]]), mean(noref[[met]]), mean(noref[[dmet]]))), append = TRUE, col.names = FALSE, row.names = FALSE, sep = ";", quote = FALSE)
            }
        }
    }
    if (args[2] == "rmicorr") {
        write.table(t(c(cor(as.numeric(unlist(mydata["PrevRMI"])), as.numeric(unlist(mydata["Refact_Sum"])), method="spearman"), cor.test(as.numeric(unlist(mydata["PrevRMI"])), as.numeric(unlist(mydata["Refact_Sum"])), method="spearman")$p.value)), append = TRUE, col.names = FALSE, row.names = FALSE, sep = ";", quote = FALSE)
    }
}
