# ---------------------------------------------------------------------------
# ex5_fixed_TRTAN_54_81.R  (workflow: r-training-exercises-for-sas-programmers)
# Reproduces: Exercise 5 with TRTAN codes 54 and 81 in place of 1 and 2. Only the codes change.
# Usage: Rscript ex5_fixed_TRTAN_54_81.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/ex5_fixed_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"))

backbone <- adsl %>% filter(SAFFL == "Y") %>% distinct(USUBJID, TRTAN = TRT01AN)

hadevent <- adae %>%
  filter(TRTEMFL == "Y", AESER == "Y") %>%
  distinct(USUBJID, TRTAN) %>%
  mutate(EVENT = 1L)

fisher2 <- backbone %>%
  left_join(hadevent, by = c("USUBJID", "TRTAN")) %>%
  mutate(EVENT = coalesce(EVENT, 0L)) %>%
  arrange(TRTAN)

run_fisher <- function(d, trts, label) {
  x   <- d %>% filter(TRTAN %in% trts)
  tab <- table(TRTAN = factor(x$TRTAN, levels = trts),
               EVENT = factor(x$EVENT, levels = c(0, 1)))
  print(label); print(tab)
  tibble(comparison = label, p_two_sided = fisher.test(tab)$p.value)
}

res <- bind_rows(
  run_fisher(fisher2, c(0, 81), "high dose vs placebo"),
  run_fisher(fisher2, c(0, 54), "low dose vs placebo")
)
print(res)

# CHECK: events per treatment vs AOCC02FL
print(fisher2 %>% group_by(TRTAN) %>% summarise(events = sum(EVENT)))
print(adae %>% filter(AOCC02FL == "Y", SAFFL == "Y") %>% count(TRTAN))
