#!/usr/bin/env Rscript
suppressMessages(library(docopt))
"Usage: gather [options]

Options:
  -s                  Run in safe mode (don't delete originals and logs)?  Default: FALSE
  -h                  Show this help screen" -> doc
opt <- docopt(doc)

# Determine which file to gather + suffixes present
files <- list.files(pattern='tmp[[:alnum:]]+.*\\.rds')
if (length(files) == 0) stop('Nothing to gather!')
suffixes <- unique(gsub('\\.rds', '', gsub('tmp[[:alnum:]]+', '', files)))

for (suffix in suffixes) {

  # Gather results into res
  res <- NULL
  types <- c('numeric', 'character', 'array', 'matrix')
  if (suffix == '') {
    suffix_pattern <- 'tmp[[:alnum:]]+\\.rds'
  } else {
    suffix_pattern <- paste0('tmp[[:alnum:]]+', suffix, '\\.rds')
  }
  for (f in list.files(pattern=suffix_pattern)) {
    res.f <- readRDS(f)
    if (class(res.f)[1] == 'list') {
      if (is.null(res)) {
        res <- res.f
        names(res) <- names(res.f)
      } else {
        rc <- sapply(res.f, function(x) class(x)[1])
        for (i in 1:length(rc)) {
          if (rc[i] %in% types) {
            res[[i]] <- abind::abind(res[[i]], res.f[[i]], along = 1)
          } else {
            stop(paste0('Cannot gather results of type ', rc[i]))
          }
        }
      }
    } else {
      if (is.null(res)) {
        res <- res.f
      } else {
        if (class(res.f)[1] %in% types) {
          res <- abind::abind(res, res.f, along = 1)
        } else {
          stop(paste0('Cannot gather results of type ', class(res.f)))
        }
      }
    }
  }

  # Output
  saveRDS(res, file=paste0(Sys.Date(), suffix, '.rds'))
}

# Delete old files
if (!opt$s) {
  for (f in files) {
    file.remove(f)
  }
  for (f in list.files(pattern='\\..*\\.log', all.files=TRUE)) {
    file.remove(f)
  }
}
