# ---------------------------------------------------------------------------
# ex4_solution_as_written.R  (workflow: r-training-exercises-for-sas-programmers)
# Reproduces: Exercise 4 solution as written: serious TEAE counts by SOC and preferred term, checked against AOCC04FL.
# Usage: Rscript ex4_solution_as_written.R <data_dir>
#   data_dir = folder containing the input files below (default: current folder).
# Input files: adam_adsl.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/ex4_output.txt in this workflow's folder.
# Packages: dplyr 1.2.1, haven 2.5.5, stringr 1.6.0, tidyr 1.3.2. 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
library(haven); library(dplyr); library(tidyr); library(stringr)

adsl <- read_xpt(file.path(data_dir, "adam_adsl.xpt"))
adae <- read_xpt(file.path(data_dir, "adam_adae.xpt"))

sas_round <- function(x, d = 1) sign(x) * floor(abs(x) * 10^d + 0.5 + 1e-9) / 10^d

denom <- adsl %>%
  filter(SAFFL == "Y") %>%
  group_by(TRTAN = TRT01AN) %>%
  summarise(denom = n_distinct(USUBJID), .groups = "drop") %>%
  arrange(TRTAN)

resultpt <- adae %>%
  filter(TRTEMFL == "Y", AESER == "Y") %>%
  group_by(TRTAN, AEBODSYS, AEDECOD) %>%
  summarise(count = n_distinct(USUBJID), events = n(), .groups = "drop") %>%
  left_join(denom, by = "TRTAN") %>%
  mutate(SUMMARYLEVEL = 3L,
         pct    = sas_round(100 * count / denom, 1),
         RESULT = sprintf("%d (%.1f%%) [%d]", count, pct, events)) %>%
  arrange(AEBODSYS, AEDECOD, TRTAN)

print(denom)
print(resultpt, n = 30)

# CHECK against AOCC04FL (first serious TEAE per subject, SOC and PT)
flag_counts <- adae %>%
  filter(AOCC04FL == "Y") %>%
  count(TRTAN, AEBODSYS, AEDECOD, name = "n_flag")
cmp <- resultpt %>%
  filter(AEDECOD != "") %>%
  full_join(flag_counts, by = c("TRTAN", "AEBODSYS", "AEDECOD"))
cat("cells where count differs from AOCC04FL:",
    sum(is.na(cmp$count) | is.na(cmp$n_flag) | cmp$count != cmp$n_flag), "\n")
