#'  MODIStsp_launcher
#' @description Utility to launch MODIStsp from batch/bash file
#' @details This script is used from the batch launchers MODIStsp.sh and MODIStsp.bat to 
#'  launch MODIStsp using Rscript (do not run it; launch from MODIStsp.sh or MODIStsp.bat).
#'  It reads three external parameters (respectively "MODIStsp_dir", "gui" and 
#'  "options_file"; see MODIStsp() for details) storing them in the variable "Args"; the 
#'  first one is automatically generated by the batch/bash scripts; others are optional.
#' @param MODIStsp_dir main directory of the local installation of the tool(if not given,
#'   it is automatically retrieved, but this works only if the function is launched from 
#'   here!)
#' @param gui logical parameter (TRUE: the GUI is opened before processing; FALSE: the 
#'   saved parameters are directly passed)
#' @param options_file settings (optional): full path of the JSON file containing the
#'   processing options (default: Previous.json in subdir Previous);
#' @return NULL
#' @author Luigi Ranghetti, phD (2015) \email{ranghetti.l@@irea.cnr.it}
#' @note License: GPL 3.0

Args <- commandArgs(TRUE)

require(MODIStsp)
require(jsonlite)

MODIStsp_dir <- system.file(package = "MODIStsp")

gui <- if (length(Args) >= 1) {
  as.logical(Args[1])
} else{
  TRUE
}
options_file <- if (length(Args) >= 2) {
  if (Args[2] == "" | Args[2] == "NULL") {
    NULL
  } else {
    Args[2]
  }
} else {
  NULL
}

if (!is.null(options_file)) {
  general_opts <- jsonlite::fromJSON(
    gsub("\\\\", "/", readLines(options_file))
  )
  log_dir <- file.path(general_opts$out_folder, "Log" )
} else {
  log_dir <- file.path(MODIStsp_dir, "Log")
}
dir.create(log_dir, showWarnings = FALSE)
# File to store the Log
outFile <- file.path(log_dir, 
                     paste0("MODIStsp_", strftime(Sys.time(), "%y%m%d_%H%M%S"),
                            ".Rout"))

sink(outFile, split = TRUE, type = c("output"))
output <- MODIStsp(gui = gui, options_file = options_file)
sink(type = c("output"))
