lag = 1
sdate = '2017'
nyears = 10
inimonth = 1
DatesSequence <- function(sdate, inimonth, finalmonth, lag, nyears) {
  if (!is.numeric(sdate)) {
     sdate <- as.numeric(sdate)
  }
  sequence <- unlist(lapply(sdate, function(x) {
                a <- paste0((sdate + lag): (sdate + nyears), 
                           sprintf('%02d', inimonth))
                b <- paste0((sdate + lag): (sdate + nyears),
                          sprintf('%02d', finalmonth))
                return(paste0(a, '-', b))}))
  sequence <- array(sequence, 
                    c(sdate = length(sdate), 
                      chunk = length(sequence)/length(sdate)))
  return(sequence)
}

path <- '/esarchive/exp/CMIP6/dcppA-hindcast/hadgem3-gc31-mm/cmip6-dcppA-hindcast_i1p1/DCPP/MOHC/HadGEM3-GC31-MM/dcppA-hindcast/r1i1p1f2/Omon/tos/gn/v20200417/$var$_Omon_HadGEM3-GC31-MM_dcppA-hindcast_s$sdate$-r1i1p1f2_gn_$chunk$.nc'

sdates <- c('2017', '2018')
chunks <- DatesSequence(sdates,
              inimonth = 1, finalmonth = 12, lag = 1, nyears = 3)
library(startR)
dat <- Start(dat = path,
             var = 'tos',
             sdate = sdates,
             chunk = values(chunks),
             chunk_depends = 'sdate',
             time = 'all',
             i = indices(1),
             j = 'all',
             time_across = 'chunk',
             merge_across_dims = TRUE,
             retrieve = TRUE,
             return_vars = list(time = 'sdate'))
attributes(dat)$NotF
attributes(dat)$Files

one <- Start(dat =  '/esarchive/exp/CMIP6/dcppA-hindcast/hadgem3-gc31-mm/cmip6-dcppA-hindcast_i1p1/DCPP/MOHC/HadGEM3-GC31-MM/dcppA-hindcast/r1i1p1f2/Omon/tos/gn/v20200417/$var$_Omon_HadGEM3-GC31-MM_dcppA-hindcast_s2018-r1i1p1f2_gn_202201-202212.nc',
              var = 'tos', time = 'all', i = 'all', j = 'all', retrieve = TRUE)

library(ncdf4)
onef <- nc_open(onef)
one <- ncvar_get(onef, 'tos')
nc_close(onef)
all(one[1,1,1,,] == dat[1,1,2,39,,]) 
for (i in 1:60) {
#print(i)
  if (all(one[1,1,1,,] == dat[1,1,2,i,,], na.rm = T)) {
    print(i)
  }
}
library(ragg)
agg_png('/esarchive/scratch/nperez/plot2.png')
image(1:1440, 1:1205, one[1,1,1,,])
dev.off()


library(ragg)
agg_png('/esarchive/scratch/nperez/plot.png')
image(1:1440, 1:1205, dat[1,1,2,37,,])
dev.off()

dat <- Start(dat = path,
             var = 'tos',
             sdate = sdates,
             chunk = 'all',
             chunk_depends = 'sdate',      
             time = 'all',
             i = 'all',
             j = 'all',
             #split_multiselected_dims = TRUE,
             time_across = 'chunk',
             largest_dims_length = TRUE, 
             merge_across_dims = TRUE,
             retrieve = TRUE,
             return_vars = list(time = NULL))
attributes(dat)$NotF
attributes(dat)$Files
