library(startR)
library(lubridate)
lats <- c(51.30760, 51.97100, 52.10000, 54.01486, 55.00690, 55.19500, 51.94355,
          53.51917, 46.95580, 53.12750, 50.92847, 52.16630, 53.40360, 55.35277,
          55.11070, 62.90566, 67.36186)
lons <- c(4.519800, 4.926000, -0.416700, 6.587639, 13.154200, 7.158000, 1.922200,
          10.102861, 16.652200, 0.436100, 6.219629, 14.122600, 6.352800, -7.332018,
          36.597700,27.653497,26.637833)
data <- Start(
                time = 'all',
                ensemble = 'all',
                sdate = format(ymd(paste0(1993:2016, sprintf('%02d',12), "01")), "%Y%m%d"),
                latitude = values(lats),
                longitude = values(lons),
                var = 'sfcWind',
                dat = '/esarchive/exp/ecmwf/system5c3s/monthly_mean/$var$_f6h/$var$_$sdate$.nc',
                pattern_dims = 'dat',
                synonims = list(latitude=c('lat', 'latitude'),longitude=c('lon', 'longitude')),
                return_vars = list(time = NULL,
                                latitude = 'dat',
                                longitude = 'dat'),
                retrieve = TRUE)
attributes(data)$Variables$dat1$lat

all(data[,,,2,,1,1] == data[,,,3,,1,1])
all(data[,,,5,,1,1] == data[,,,6,,1,1])
all(data[,,,1,,1,1] == data[,,,2,,1,1])


SinglePoints <- function(data, lons, lats) {
    if (!is.array(data)) {
       stop("Parameter 'data' must be an startR_array")
    }     
    lat <- attributes(data)$Variables$common$latitude
        if (is.null(lat)) {
            lat <- attributes(data)$Variables$dat1$latitude
        }  
        if (is.null(lat)) {
            stop("Latitudes not found in parameter 'data'.")
        }
    lon <- attributes(data)$Variables$common$longitude
        if (is.null(lon)) {
            lon <- attributes(data)$Variables$dat1$longitude
        }
        if (is.null(lon)) {
            stop("Longitudes not found in parameter 'data'.")
        }
    position_lon <- match(round(lons,0), lon)
    position_lat <- match(round(lats,0), lat)
    return(list(lon = lon[position_lon], lat = lat[position_lat]))
}
   
# Could I create a transform function to obtain gridpoint or regions instead of lat.lon?
source("/esarchive/scratch/nperez/git/startR/R/Start.R")
source("/esarchive/scratch/nperez/git/startR/R/NcOpener.R")
source("/esarchive/scratch/nperez/git/startR/R/NcCloser.R")
source("/esarchive/scratch/nperez/git/startR/R/NcDimReader.R")
source("/esarchive/scratch/nperez/git/startR/R/NcVarReader.R")
source("/esarchive/scratch/nperez/git/startR/R/NcDataReader.R")
source("/esarchive/scratch/nperez/git/startR/R/Utils.R")
source("/esarchive/scratch/nperez/git/startR/R/SelectorChecker.R")
