library(startR)

# This is a fake example. I read one file of system5_m1 to get the latitudes and longitudes in a region, to create a consistent mask:
repos <- '/esarchive/exp/ecmwf/system5_m1/monthly_mean/$var$_f6h/$var$_$sdate$.nc'
data <- Start(dat = repos,
              var = 'tas',
              sdate = c('20170101', '20180101'),
              ensemble = indices(1:20),
              time = 'all',
              latitude = indices(300:341),
              longitude = indices(1:40),
              return_vars = list(latitude = 'dat',
                                 longitude = 'dat',
                                 time = 'sdate'),
              retrieve = FALSE)

# I create a fake mask with one's and zero's:
mask <- rep(c(rep(1, 21), rep(0, 21)), 40)
dim(mask) <- c(latitude = 42, longitude = 40)

attr(mask, 'longitude') <- attributes(data)$Variables$dat1$longitude
attr(mask, 'latitude') <- attributes(data)$Variables$dat1$latitude

library(ncdf4)
dim_lon <- ncdim_def(name = 'longitude', units = 'degrees',
                     vals = as.vector(attributes(data)$Variables$dat1$longitude),
                     longname = 'longitude')
dims_var[[1]] <- dim_lon
dim_lat <- ncdim_def(name = 'latitude', units = 'degrees_north',
                     vals = as.vector(attributes(data)$Variables$dat1$latitude),
                     longname = 'latitude')
dims_var[[2]] <- dim_lat
datanc  <- ncvar_def(name = 'mask',
                     units = 'adimensional',
                     dim = dims_var, missval = -99999)
file_nc <- nc_create("/esarchive/scratch/nperez/mask_system5_m1_harvestmonth.nc",
                     datanc)
ncvar_put(file_nc, datanc, mask)
nc_close(file_nc)

# Check you can loaded with Start()
path_mask <- "/esarchive/scratch/nperez/$var$_system5_m1_harvestmonth.nc"
mask_loaded <-  Start(dat = path,
               var = 'mask',
               latitude = 'all',
               longitude = 'all',
               return_vars = list(latitude = 'dat',
                                  longitude = 'dat'),
               retrieve = TRUE)





