# ---------------------------------------------------------------------------
# run_bad.R  (workflow: fda-ir-replication-instructions)
# Reproduces: Runs the steps of the vague-input plan literally and shows where it fails (PARAMCD ADAS13, REGION and FASFL do not exist in the pilot data; mmrm is not installed).
# Usage: Rscript run_bad.R <data_dir>
#   data_dir = folder containing the input files below (default: current folder).
# Input files: adam_adsl.xpt; adam_adqsadas.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/run_bad_output.txt in this workflow's folder.
# Packages: dplyr 1.2.1, haven 2.5.5, mmrm base/recommended. 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.
# ---------------------------------------------------------------------------
# Executes the lazy-input plan's step 3 to 6 literally on the unmodified CDISC pilot data.
# Usage: Rscript run_bad.R <folder containing adam_adsl.xpt and adam_adqsadas.xpt>
suppressMessages({library(haven); library(dplyr)})
d <- if (length(commandArgs(TRUE)) >= 1) commandArgs(TRUE)[1] else "."
adsl <- read_xpt(file.path(d, "adam_adsl.xpt")); adqs <- read_xpt(file.path(d, "adam_adqsadas.xpt"))
cat("Does the plan's PARAMCD = 'ADAS13' exist in ADQSADAS? ", "ADAS13" %in% adqs$PARAMCD, "\n")
cat("PARAMCD values present: ", paste(unique(adqs$PARAMCD), collapse = " "), "\n")
cat("Does the plan's REGION exist in ADSL or ADQSADAS? ", any(c("REGION") %in% c(names(adsl), names(adqs))), "\n")
cat("Does ADSL have FASFL? ", "FASFL" %in% names(adsl), "\n")
anl <- adqs %>% inner_join(filter(adsl, ITTFL == "Y") %>% select(USUBJID, TRT01P), by = "USUBJID") %>%
  filter(PARAMCD == "ADAS13", ANL01FL == "Y", AVISITN > 0)
cat("Rows left after the plan's filter (PARAMCD == 'ADAS13'): ", nrow(anl), "\n")
cat("Is the mmrm package installed? ", requireNamespace("mmrm", quietly = TRUE), "\n")
