# run_adae_from_spec.R: harness (NOT AI code). Reads the CDISC pilot files, runs adae_from_spec.R, compares with adam_adae.xpt.
# Usage: Rscript run_adae_from_spec.R <data_dir>   (data_dir holds sdtm_ae.xpt, adam_adsl.xpt, adam_adae.xpt)
# Needs: haven, dplyr. Keep adae_from_spec.R in the same folder. Licence: MIT (LICENSE.txt). Data: CDISC pilot, not included.
# Optional 2nd argument: "raw" (no date conversion; stops with an error), or "fix" to correct the SOC spelling and the ADURN rule (two edits the comparison pointed to).
args <- commandArgs(trailingOnly = TRUE)
data_dir <- if (length(args) >= 1) args[1] else "."
fix <- "fix" %in% args[-1]
raw <- "raw" %in% args[-1]   # raw = do not convert dates: reproduces the first run, which stops with an error
script_dir <- local({ f <- sub("^--file=", "", grep("^--file=", commandArgs(FALSE), value = TRUE))
                      if (length(f)) dirname(normalizePath(f[1])) else "." })
suppressMessages(library(haven)); suppressMessages(library(dplyr))
ae   <- as.data.frame(read_xpt(file.path(data_dir, "sdtm_ae.xpt")))
adsl <- as.data.frame(read_xpt(file.path(data_dir, "adam_adsl.xpt")))
ref  <- as.data.frame(read_xpt(file.path(data_dir, "adam_adae.xpt")))
cat("class of ADSL TRTSDT as read:", class(adsl$TRTSDT)[1], "\n")
if (!raw && inherits(adsl$TRTSDT, "Date")) adsl$TRTSDT <- as.numeric(adsl$TRTSDT) + 3653   # the AI code expects a SAS date number; haven gives a Date
for (v in c("ASTDT", "AENDT", "TRTSDT")) if (inherits(ref[[v]], "Date")) ref[[v]] <- as.numeric(ref[[v]]) + 3653
src <- readLines(file.path(script_dir, "adae_from_spec.R"))
if (fix) {
  src <- sub("SKIN AND SUBC UTANEOUS TISSUE DISORDERS", "SKIN AND SUBCUTANEOUS TISSUE DISORDERS", src, fixed = TRUE)
  src <- c(src, 'adae$ADURN[!is.na(adae$ASTDTF) & adae$ASTDTF == "D"] <- NA; adae$ADURU <- ifelse(!is.na(adae$ADURN), "DAY", NA_character_)')
}
eval(parse(text = src))
cat("\nComparison with adam_adae.xpt:\n")
compare_adae(adae, ref, vars)
