rm(list=ls())
library(startR)
library(multiApply)

path <- '/esarchive/scratch/nperez/git/Flor/ArticXchange/climograph'
setwd(path)

vars <- c('tasmax', 'tasmin', 'tas', 'prlr')
freq <- rep('monthly_mean', 4)

lat_rovanievi <- 66.5
lon_rovanievi <- 25.75
reference_period <- 1993:2016

vars_rovanievi <- NULL
for (v in 1:length(vars)) {
  if (vars[v] %in% c('tas', 'prlr')) {
    path <- "/esarchive/recon/ecmwf/era5land/monthly_mean/$var$_f1h/$var$_$year$$month$.nc"
  } else {
    path <- "/esarchive/recon/ecmwf/era5land/monthly_mean/$var$_f24h/$var$_$year$$month$.nc"
  }
  data <- Start(
               dat = path,
               var = vars[v],
               year = as.character(reference_period),
               month = sprintf("%02d", 1:12),
               time = 'all',
               lat = startR::values(lat_rovanievi),
               lon = startR::values(lon_rovanievi),
               synonims = list(lat = c('lat', 'latitude'),
                               lon = c('lon', 'longitude')),
               num_procs = 1,
               return_vars = list(lat = NULL, lon = NULL),
               retrieve = TRUE)
print(vars[v])
print(as.vector(attributes(data)$NotFound)[which(!is.na(attributes(data)$NotFound))])
print(range(data, na.rm = TRUE))
print(as.vector(attributes(data)$Variables$common$lat))
print(as.vector(attributes(data)$Variables$common$lon))
  if (vars[v] != 'prlr') {
    clim <- drop(Apply(list(data), list('year'), fun = mean, na.rm = T)$output)
    clim <- clim - 273.15
  } else {
    clim <- drop(Apply(list(data), list('year'), fun = sum, na.rm = T)$output)
    clim <- clim * 86400 * 1000
  }
print(range(clim))
print(dim(clim))
  vars_rovanievi <- abind::abind(vars_rovanievi, clim, along = 2)  
}

#----------------- CLIMOGRAPH -------------------------
par(mar = c(5.5, 4, 4, 4))
barplot(vars_rovanievi[,4], col = "lightgreen", ylab = "Precipitation (mm)",
        names = month.abb[1:12], border = "darkgreen", ylim = c(0, 67), las = 2)
par(new = TRUE)
plot(1:12, vars_rovanievi[,3], col = "darkred", typ = "l",  lwd = 3,
     xaxt = 'n', yaxt = 'n',  ylab = '', xlab = '')
axis(side = 4, at = pretty(range(vars_rovanievi[,1])))
mtext("Temperature (ºC)", side = 4, line = 3)
dev.new()
# -------------- Plot Climogrpah -----------------------
#  Including tasmax and tasmin -------------------------
par(mar = c(5.5, 4, 4, 4))
matplot(1:12, vars_rovanievi[,1:3], type = 'l', xaxt = 'n',
        col = c('darkred', 'darkblue', 'orange'), xlab = '',
        ylab = 'temperature (degreesC)',
        main = paste('Rovanievi Climatology',
                     paste(range(reference_period), collapse = '-')))
par(new = TRUE)
plot(1:12, vars_rovanievi[,4], type = 'h', xaxt = 'n', yaxt = 'n',  ylab = '',
     lwd = 3, col = 'darkgreen', xlab = '')
axis(side = 4, at = pretty(range(vars_rovanievi[,4])))
mtext("Total precipitation (mm)", side=4, line = 3)
axis(1, 1:12, month.name, las = 2)
legend('topleft', vars, col = c('darkred', 'darkblue', 'orange', 'darkgreen'),
       pch = 16, bty = 'n')
# -------------------------------------
dev.new()
par(mar = c(5.5, 4, 4, 4))
barplot(vars_rovanievi[,4], col = "lightgreen", ylab = "Precipitation (mm)",
        names = month.abb[1:12], border = "darkgreen", ylim = c(0, 67), las = 2,
        main = "ERA5 Land (1993-2016) Rovaniemi")
par(new = TRUE)
matplot(1:12, vars_rovanievi[,1:3], col = c("darkred", "darkblue", "orange"), 
        typ = "l",  lwd = 3,
        xaxt = 'n', yaxt = 'n',  ylab = '', xlab = '')
axis(side = 4, at = pretty(range(vars_rovanievi[,1])))
mtext("Temperature (ºC)", side = 4, line = 3)

