# To run with internet connexion
library(CSTools); library(raster); library(s2dv)
worldclim <- getData("worldclim", var = "prec", res = 0.5, lon = 5, lat = 45)
wc_month <- lapply(1:12, FUN = function(x) {
                   res <- crop(worldclim[[x]],
                               extent(3.5, 11.5, 41.5, 49.5))
                   res <- as.array(res)
                   names(dim(res)) <- c('lat', 'lon', 'month')
                   return(res)
                   })


xy <- xyFromCell(crop(worldclim[[1]], extent(3.5, 11.5, 41.5, 49.5)),
                 1:length(crop(worldclim[[1]], extent(3.5, 11.5, 41.5, 49.5))))
lons <- unique(xy[,1])
lats <- unique(xy[,2])
wc_month <- unlist(wc_month)
dim(wc_month) <- c(lat = length(lats), lon = length(lons), monthly = 12)
wc_month <- Reorder(wc_month, c('lon', 'lat', 'monthly'))
wc_month <- s2dv_cube(data = wc_month, lon = lons, lat = lats,
                       Datasets = 'WorldClim')
weight <- CST_RFWeights(wc_month, lon = 4:11, lat = 49:42, nf = 100)
save(weight,
     file = '/esarchive/scratch/nperez/CSTools_manuscript/weightsRF100.RDS', version = 2)
