# Runs each pre-registered association on the cycles its paper analyzed (the coding check) and,
# unless --original-only is given, on NHANES August 2021-August 2023 (the replication), and
# summarizes them: results/associations.json and results/R1.json (results/reproduction.json and
# results/reproduction_summary.json with --original-only).

suppressPackageStartupMessages(library(survey))
options(survey.lonely.psu = "adjust", warn = 1, stringsAsFactors = FALSE)
for (module in c("cycles", "io", "design", "model", "stats", "variables", "covariates", "indices", "liver", "pipeline", "summary")) {
  source(file.path("code", "lib", paste0(module, ".R")))
}

args <- commandArgs(trailingOnly = TRUE)
replication <- !"--original-only" %in% args
only <- unlist(strsplit(sub("^--only=", "", grep("^--only=", args, value = TRUE)), ","))

results <- run_all(load_associations(only), replication)
dir.create("results", showWarnings = FALSE)
write_json(results, if (replication) "results/associations.json" else "results/reproduction.json")
write_json(summarize_results(results, replication), if (replication) "results/R1.json" else "results/reproduction_summary.json")
# The NHANES files this run read, as "cycle file".
writeLines(sort(ls(.files)), "results/files_read.txt")
