# Wageningen Environmental Research
# waterwijzerlandbouw@wur.nl
#------------------------------------------------

# set start of program
TIMPRGSTART <- Sys.time()

# --- arguments ---

# set modus
test <- FALSE

# load arguments
if (!test) {
  command_args <- commandArgs(trailingOnly = TRUE)
  if (length(command_args) != 1) stop("wrong usage of script, arguments should be:\n- controlfile")
} else {
  setwd("c:/WaterwijzerLandbouw/WWL_regionaal")
  command_args <- NULL
  command_args[1] <- "control_meteo.inp"
}

# set arguments
ctrl <- command_args[1]

# --- load libraries ---

source("tools/R/libraries_meteo.R")

message("\nProgram R-PROG started...\n")

# --- initial part of procedure ---

# load controlfile
text <- read_lines(file = ctrl, lazy = FALSE, num_threads = 1, progress = FALSE)

# set directories
dir_out <- get_dir(text = text, item = "DIROUT", create = FALSE)

# set station KNMI
station <- get_record(text = text, item = "STATION")
replace <- get_record(text = text, item = "REPLACE", item_exists = FALSE)

# set period
tstart <- get_record(text = text, item = "TSTART")
tend <- get_record(text = text, item = "TEND")

# split met-files
split <- get_switch(text = text, item = "SPLIT", item_exists = FALSE, default = FALSE)

# --- main part of procedure ---

# create met-file(s)
create_meteo_SWAP(dir_out = dir_out, station = station, tstart = tstart, tend = tend, split = split, replace = replace)

# --- return of procedure ---

TIMPRGEND <- Sys.time()
TIMPRGCALC <- as.numeric(difftime(time1 = TIMPRGEND, time2 = TIMPRGSTART, units = "secs"))
message(paste0("\nProgram R-PROG successfully ended in ", floor(TIMPRGCALC / 60), " minutes and ", ceiling(TIMPRGCALC %% 60), " seconds"))
q(save = "no")
