
library(ggplot2)
library(grid)
library(rworldmap)
library(easyNCDF)
library(rgdal)

ref.file <- '/esarchive/recon/ecmwf/era5/daily_mean/tas_f1h/tas_201001.nc'
mask.file <- '/esarchive/scratch/lpalma/scripts/decathlon/masks/regions-polygon.shp'
outfile <- '/esarchive/scratch/lpalma/scripts/decathlon/masks/era5-decathlon.nc'

lat <- NcToArray(ref.file, vars_to_read='latitude')
lon <- NcToArray(ref.file, vars_to_read='longitude')
lat <- lat[1,]
lon <- lon[1,]
lon <- ((lon + 180) %% 360) - 180

shp <- rgdal::readOGR(mask.file)

mask <- array(0, dim = c(length(lon), length(lat)))
regions <- c(11)
for (reg in 1:11){
  reg.lats <- slot(slot(attributes(shp)$polygons[[reg]],"Polygons")[[1]],"coords")[,2] #lat
  reg.lons <- slot(slot(attributes(shp)$polygons[[reg]],"Polygons")[[1]],"coords")[,1] #lon
  in.country <- function(lon,lat){
      point.in.polygon(lon,lat,reg.lons,reg.lats)
  }
  mask.reg <- outer(lon,lat,in.country)
  mask <- mask + mask.reg 
}
mask[which(mask > 1 , arr.ind=T)] <- 1

names(dim(mask)) <- c('longitude', 'latitude')
get_latlon <- function(lat, lon){

    longitude <- lon
    dim(longitude) <- length(longitude)
    metadata <- list(longitude = list(units = 'degrees_east'))
    attr(longitude, 'variables') <- metadata
    names(dim(longitude)) <- 'longitude'
    
    latitude <- lat
    dim(latitude) <- length(latitude)
    metadata <- list(latitude = list(units = 'degrees_north'))
    attr(latitude, 'variables') <- metadata
    names(dim(latitude)) <- 'latitude'

    return(list(lat=latitude,lon=longitude))
}

grid <- get_latlon(lat,lon)
ArrayToNc(list(mask, grid$lat, grid$lon),outfile) 

