# Put contents of mtcars into temporary file.
# Retrieve the number of variables and observations.
fstring <- gsub('[ ][ ]*',' ',readChar(fnam, file.info(fnam)$size))
obs <- as.numeric(gsub('Observations ','',stringr::str_extract(fstring,'Observations [0-9][0-9]*')))
vrs <- as.numeric(gsub('Variables ','',stringr::str_extract(fstring,'Variables [0-9][0-9]*')))
# We know there are 11 variables and 32 observations in mtcars.

test_that("converting data to codelist works", {
# Build a codelist style format off of a SAS data set containing a SAS format.
clist <- c(list$SEXS$START[[1]], list$SEXS$LABEL[[1]], list$SEXS$START[[2]], list$SEXS$LABEL[[2]])
# Check that the resulting codelist is as expected.

iris1 <- iris %>% dplyr::mutate(ID=dplyr::row_number())
iris2 <- iris %>% dplyr::mutate(ID=dplyr::row_number()) %>% dplyr::mutate(Petal.Length=Petal.Length+1)
irisdiffs <- repfun::ru_datacompare(iris1, iris2, idvars=c('Species','ID'))

test_that("adding formatted datetimes works", {
# Read SDTM.AE and add time values to the dates.
# Invoke the function ru_datetime() to create formatted datetime variables from the strings.
# Convert the new datetime versions to strings and compare back with the original strings for a match.
ae3 %>% dplyr::mutate(NEW_AEDTC = gsub(' ','T',trimws(as.character(AEDTM))),
AEENDTC = ifelse(nchar(AEENDTC)<10,NA,AEENDTC)) -> ae4

test_that("transposing a dataframe works", {
repfun::rs_setup(D_POP="SAFFL",D_POPLBL="Safety",D_POPDATA=repfun::adsl %>% filter(SAFFL =='Y'), D_SUBJID=c("STUDYID","USUBJID"), R_ADAMDATA=".")
aeprod_t <- repfun::ru_denorm(aesum,varstodenorm=c("tt_result", "PERCENT"), groupbyvars=c("tt_summarylevel", "AEBODSYS", "AEDECOD"),
acrossvar="TRT01AN", acrossvarlabel="TRT01A", acrossvarprefix=c("tt_ac", "tt_p")) %>%
aeqc_t <- aesum %>% dplyr::select(tt_summarylevel, AEBODSYS, AEDECOD, TRT01AN, tt_result, PERCENT) %>%
dplyr::group_by(tt_summarylevel, AEBODSYS, AEDECOD) %>% tidyr::pivot_wider(names_from=TRT01AN, values_from=c(tt_result, PERCENT)) %>%
tt_p01=PERCENT_1,tt_p02=PERCENT_2,tt_p03=PERCENT_3,tt_p99=PERCENT_99) %>% repfun::ru_labels(varlabels=lapply(aeprod_t, attr, "label")) %>%
dplyr::select(names(aeprod_t)) %>% dplyr::arrange(tt_summarylevel, AEBODSYS, AEDECOD)
# Baseline Characteristics Summary Stats Test
statslist=c("n", "mean", "median", "sd", "min", "max"))
demprod_t <- repfun::ru_denorm(demstats, varstodenorm=c("tt_result"), groupbyvars=c("tt_avid", "tt_avnm", "tt_svid", "tt_svnm"),
demqc_t <- demstats %>% dplyr::select(tt_avid,tt_avnm,tt_svid,tt_svnm,TRT01AN,tt_result) %>% dplyr::mutate(TRT01AN=sprintf("%02d",TRT01AN)) %>%
dplyr::group_by(tt_avid,tt_avnm,tt_svid,tt_svnm) %>% tidyr::pivot_wider(names_from=TRT01AN, values_from=c(tt_result), names_prefix="tt_ac") %>%
repfun::ru_labels(varlabels=lapply(demprod_t, attr, "label")) %>% dplyr::select(names(demprod_t)) %>% dplyr::arrange(tt_avid,tt_avnm,tt_svid,tt_svnm)