
help_message <- "This script is used to merge the results generated by gcta_cis.R for different chromosomes.
Usage: Rscript merge_cis_res.R [options]

Options:
  --file_dir=value   Directory of output results for gcta_cis.R
  --help         Display this help message.
"

args <- commandArgs(trailingOnly = TRUE)

if ("--help" %in% args) {
  cat(help_message)
  quit("no", status = 0)
}

for (arg in args) {
  if (startsWith(arg, "--file_dir=")) {
    file_dir <- gsub("--file_dir=", "", arg)
  }
}


file_list <- list.files(file_dir, pattern="gcta_cis_pred_.*.RData", full.names=T)

res_vc_m <- c();
res_cis_m <- c();
res_trans_m <- c();
res_pred_m <- c()
for(res_file in file_list){
   #print(chr)
   #res_file <- sprintf("%s/gcta_cis_pred_%s.RData", file_dir, chr)
   if(!file.exists(res_file)){ print(sprintf("%s not exists!", res_file)); next}
   (load(res_file))
   res_vc_m <-  rbind(res_vc_m,  res$res_vc)
   res_cis_m <-  rbind(res_cis_m,  res$res_cis)
   res_trans_m <-  rbind(res_trans_m,  res$res_trans)
   res_pred_m <-  rbind(res_pred_m,  res$res_pred)
}
res_vc_m <- na.omit(res_vc_m)
res_vc_m[which(res_vc_m$pvalue==0),"pvalue"] <- 5e-17
save(res_vc_m, file=sprintf("%s/gcta_cis_vc.RData", file_dir))
save(res_cis_m, file=sprintf("%s/gcta_cis_cis.RData", file_dir))
save(res_trans_m, file=sprintf("%s/gcta_cis_trans.RData", file_dir))
save(res_pred_m, file=sprintf("%s/gcta_cis_pred.RData", file_dir))

