# -----------------------------
# function to load data
# -----------------------------


loadData <- function(clim_var, mth) {
  
  # load libraries
  library(s2dverification)
  library(ncdf)
  
  
  # specify grid
  if (clim_var == "tas") {
    grid <- "256x128"
    obs = c('erainterim') #c('ghcn_v2') #
  } else {
    grid <- "144x72"
    obs = c('gpcp_v2.2')
  }
  fnc <- open.ncdf("/esarchive/autosubmit/con_files/land_sea_mask_1x1_c3s.nc")
  fnc <- nc_open("/esarchive/autosubmit/con_files/land_sea_mask_1x1_c3s.nc")
  lataux <- get.var.ncdf(fnc,"lat")
  maskaux <- get.var.ncdf(fnc,"LSM")
  close.ncdf(fnc)
  # mask for MODEL
  fnc <- open.ncdf(paste("/esnas/exp/ecearth/land_sea_mask_", grid, ".nc", sep = ""))
  lataux <- get.var.ncdf(fnc,"lat")
  maskaux <- get.var.ncdf(fnc,"LSM")
  close.ncdf(fnc)
  
  nlat=length(lataux)
  if (lataux[1]>0){
    lataux=rev(lataux)
    maskmod=maskaux[,seq(nlat,1)]
  }else{
    maskmod=maskaux
  }
  
  maskmod[which(maskmod > 0.5)] <- 1
  maskmod[which(maskmod < 0.5)] <- 0
  
  listmaskmod=list(maskmod, maskmod, maskmod, maskmod)
  
  
  # mask for OBSERVATION
  
  # fnc <- open.ncdf(paste("/esnas/exp/ecearth/land_sea_mask_", grid, ".nc", sep = ""))
  # maskobs <- get.var.ncdf(fnc,"LSM")
  # close.ncdf(fnc)  
  # 
  # 
  # maskobs[which(is.na(maskmod))] <- 1 
  # 
  # listmaskobs=list(maskobs)
  
  
  # masklst=list(paste("/esnas/exp/ecearth/land_sea_mask_", grid, ".nc", sep = ""))
  
  
  # create date seq
  start <- as.Date(paste("1992", mth, "01", sep = ""), "%Y%m%d")
  end <- as.Date(paste("2012", mth, "01", sep = ""), "%Y%m%d")
  dateseq <- format(seq(start, end, by = "year"), "%Y%m%d")
  
  
  glosea5 <- list(path = '/esnas/exp/glosea5/specs-seasonal_i1p1/$STORE_FREQ$_mean/$VAR_NAME$-allmemb/$VAR_NAME$_$START_DATE$.nc')
  
  StartData <- Load(clim_var, 
                    exp = list(glosea5,
                               list(name = 'ecmwf/system4_m1'),
                               list(name = 'ncep/system2_m1'),
                               list(name = 'meteofrance/system5_m1')),
                    obs = obs,
                    sdates = dateseq, 
                    leadtimemin = 2, leadtimemax = 4,
                    lonmin = -20, lonmax = 70, 
                    latmin = 25, latmax = 75, 
                    storefreq = "monthly", sampleperiod = 1, 
                    nmember = 9, output = "lonlat",
                    method = "bilinear",
                    maskmod = listmaskmod,  
                    #maskobs = listmaskobs, 
                    grid = paste("r", grid, sep = ""))
  
  return(StartData)
}