rm(list=ls())
library(ncdf4)
library(abind)
library(fields)
library(CSTools)
library(RColorBrewer)
library(s2dv)
library(ggplot2)
library(startR)
library(multiApply)
# Load 1 start date
args = commandArgs(trailingOnly = TRUE)
sdates <- args[1]
# Nuria's code to load the dates and name the weeks
#sdates <- "20240502"
week <- format(seq(as.Date("20240104", "%Y%m%d"), as.Date("20241226", "%Y%m%d"), 7), "%Y%m%d")
weeknum <- sprintf("%02d", which(week == sdates))
figpath <- "/esarchive/scratch/ptrascas/R/sunset/"
path <- "/esarchive/exp/VITIGEOSS/subseasonal/"
region <- 'cat'
# There are some issues picking the location, numbers must be "exact"
Barcelona <- c(lat = 41.39, lon = 2.1)
Granollers <- c(lat = 41.61, lon = 2.3)
Viladecans <- c(lat = 41.32, lon = 2.0)
locations <- list(Barcelona, Granollers, Viladecans)
#locations <- list(Viladecans)
vars <- c('t2','t02min','t02max') #just for testing
for (loc in locations) {
  if (loc == Barcelona) {
    loc_name <- "Barcelona"
  } else if (loc == Granollers) {
    loc_name <- "Granollers"
  } else if (loc == Viladecans) {
    loc_name <- "Viladecans"
  }
    for (var in vars){
	# FORECAST
    	path_fcst <- paste0(path, var, "/$sdates$/", var, "_", region, "_$sdates$.nc")
    	fcst <- Start(dat = path_fcst,
    	          var = var,
       	     	  sdates = sdates,
	     	  latitude = values(loc[[1]]),
             	  longitude = values(loc[[2]]),
             	  ensemble = 'all',
             	  time = 'all',
             	  retrieve = T)
    		  as.vector(attributes(fcst)$Variables$common$latitude)
    		  as.vector(attributes(fcst)$Variables$common$longitude)
	# PROBABILITIES
    	path_probs <- paste0(path, var, "/$sdates$/", var, "_", region, "_prob_$sdates$.nc")
    	probs <- Start(dat = path_probs,
                   var = c('prob_bn', 'prob_n', 'prob_an'),
                   sdates = sdates,
                   latitude = values(loc[[1]]),
                   longitude = values(loc[[2]]),
                   time = 'all',
                   return_vars = list(latitude = NULL, longitude = NULL, time = 'sdates'),
                   retrieve = T)
        as.vector(attributes(probs)$Variables$common$latitude)
    	as.vector(attributes(probs)$Variables$common$longitude)
    	attributes(probs)$Variables$common$time
    	dim(attributes(probs)$Variables$common$time)
    	# TERCILE LIMITS
    	path_lims <- paste0(path, var, "/$sdates$/", var, "_", region,
                        "_percentiles_week$weeknum$.nc")
   	dim(week) <- c(weeks = length(week), sdates = 1)
   	lims <- Start(dat = path_lims,
                  var = c('p33', 'p66'),
                  sdates = sdates,
                  weeknum = 'all',
                  weeknum_depends = 'sdates',
                  latitude = values(loc[[1]]),
                  longitude = values(loc[[2]]),
                  time = 'all',
                  return_vars = list(latitude = NULL, longitude = NULL, time = 'sdates'),
                  retrieve = T)
	
        as.vector(attributes(lims)$Variables$common$latitude)
    	as.vector(attributes(lims)$Variables$common$longitude)
    	attributes(lims)$Variables$common$time
    	dim(attributes(lims)$Variables$common$time)
    	print(lims)
	# SKILL
	path_skill <- paste0(path, var, "/$sdates$/", var, "_", region,
                         "_skill_week$weeknum$.nc")
    	rpss <- Start(dat = path_skill,
                  var = c('rpss'),
                  sdates = sdates,
                  weeknum = 'all',
                  weeknum_depends = 'sdates',
                  latitude = values(loc[[1]]),
                  longitude = values(loc[[2]]),
                  time = 'all',
                  return_vars = list(latitude = NULL, longitude = NULL, time = 'sdates'),
                  retrieve = T)
        as.vector(attributes(rpss)$Variables$common$latitude)
    	as.vector(attributes(rpss)$Variables$common$longitude)
    	attributes(rpss)$Variables$common$time
    	dim(attributes(rpss)$Variables$common$time)
	mondays <- format(seq(as.Date(sdates, "%Y%m%d") + 4, as.Date(sdates, "%Y%m%d") + 30, 7), "%d-%m-%Y")
	sundays <- format(seq(as.Date(sdates, "%Y%m%d") + 10, as.Date(sdates, "%Y%m%d") + 40, 7), "%d-%m-%Y")
	subtit <- sapply(1:4, function(x) { paste0("Semana del\n", mondays[x], "\nal ",
	       	  sundays[x], "\nRPSS = ", round(rpss[1,1,1,1,1,1,x]/100,digits=2))})
    	# Plot forecast PDF
    	fcst <- data.frame(fcst1 = fcst[1,1,1,1,1,,1], fcst2 = fcst[1,1,1,1,1,,2], fcst3 = fcst[1,1,1,1,1,,3], fcst4 = fcst[1,1,1,1,1,,4])
    	p33 <- c(lims[1,1,1,1,1,1,1],lims[1,1,1,1,1,1,2],lims[1,1,1,1,1,1,3],lims[1,1,1,1,1,1,4])
    	p66 <- c(lims[1,2,1,1,1,1,1],lims[1,2,1,1,1,1,2],lims[1,2,1,1,1,1,3],lims[1,2,1,1,1,1,4])
    	terlims <- array(c(p33,p66), dim = c(4,2))
        	
       	# Improve this part to automatise week labels in the subplot titles:
        PlotForecastPDF(fcst,tercile.limits = terlims, var.name = "Temperatura (\u00B0C)",fcst.names =
    		subtit, title = paste0("Prediccion de temperatura en ",loc_name,"\nEmitida en ",
		format(as.Date(sdates, "%Y%m%d"), "%d-%m-%Y")), color.set="s2s4e",
		add.ensmemb = "no", plotfile = paste0(figpath, "/I4C_forecastpdf_",var,"_",loc_name,".png"))


   print(terlims) }
}


print("Greetings Palo from the misty hills of the Mordor")

