# ---------------------------------------------------------------------------
# codes.R  (workflow: submission-program-readiness-review)
# Reproduces: Counts blank or missing values in dictionary and action-taken variables of ADAE and says whether each exists in SDTM AE.
# Usage: Rscript codes.R <data_dir>
#   data_dir = folder containing the input files below (default: current folder).
# Input files: sdtm_ae.xpt; adam_adae.xpt
#   Download the unmodified files from the public CDISC pilot repository:
#   https://github.com/cdisc-org/sdtm-adam-pilot-project  (folder updated-pilot-submission-package/900172/m5/)
#   (datasets as .xpt files).
# Expected output: see expected_output/codes_output.txt in this workflow's folder.
# Packages: dplyr 1.2.1, haven 2.5.5. Tested with R 4.6.1 on Windows.
#   Install what is missing with install.packages(c(...)); no private library path is needed.
# Licence: code MIT (see README.md in the scripts folder). Data: CDISC SDTM/ADaM Pilot Project (CDISCPILOT01),
# credited to CDISC, used unmodified under the CDISC terms of use. The data are not included here.
# Logic is unchanged from the version that produced the saved output; only path handling and this header were changed.
# ---------------------------------------------------------------------------
args <- commandArgs(trailingOnly = TRUE)
data_dir <- if (length(args) >= 1) args[1] else "."   # folder holding the CDISC pilot .xpt files
script_dir <- local({ f <- sub("^--file=", "", grep("^--file=", commandArgs(FALSE), value = TRUE))
                      if (length(f)) dirname(normalizePath(f[1])) else "." })   # folder holding this script
suppressMessages({library(haven);library(dplyr)})
src <- paste0(sub("/+$", "", data_dir), "/")
adae <- read_xpt(paste0(src,"adam_adae.xpt")); ae <- read_xpt(paste0(src,"sdtm_ae.xpt"))
for (v in c("AEACN","AELLT","AELLTCD","AEPTCD","AEHLT","AEHLTCD","AEHLGT","AEHLGTCD","AESOC","AESOCCD")) {
  x <- adae[[v]]; blank <- if (is.character(x)) is.na(x)|trimws(x)=="" else is.na(x)
  cat(sprintf("%-9s in SDTM AE: %-5s  ADAE rows blank/missing: %4d of %d\n", v, v %in% names(ae), sum(blank), length(x)))
}
