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
sdates <- "20240627"
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)

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){

        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)

lims_formatted <- sprintf("%.2f", lims)
print(paste(loc_name,var,lims_formatted))

} 
} 

######### LOAD TERCILES FROM OBSERVATIONS #######


# make sure that sday = 3

# Calculate tercile limits for lt1 in observations for Barcelona, Granollers, Viladecans

Barcelona <- c(lat = 41.39, lon = 2.1)
Granollers <- c(lat = 41.61, lon = 2.3)
Viladecans <- c(lat = 41.32, lon = 2.0)

obs$data <- obs$data[1,1,1,2,,1,,]

obs$data <- obs$data - 273.15

barcelona <-

lon
[1] -4.4979858 -3.5599976 -2.6220093 -1.6839905 -0.7460022  0.0000000
 [7]  0.9380000  1.8760000  2.8139999  3.7520001  4.6900001
lat
[1] 43.93682 42.99194 42.04707 41.10219 40.15731 39.21244 38.26756 37.32269
[9] 36.37781
