#'LargeLocalScale
#' 
#'@author Carmen Alvarez-Castro, \email{carmen.alvarez-castro@cmcc.it}
#'
#'@description Select the large and the local scale and interpolate into a smaller-grid-size using cdo and daily data 
#'from a model projection, seasonal model or reanalysis 
#'
#'@param var             variable name
#'       directory       the directory folder of your data
#'       Namefilein      name of your imput file
#'       filesmallgrid   file with small gridsize to be used as a reference grid for the interpolation
#'       large.lonlat    large scale longitude and latitude as lon1,lon2,lat1,lat2
#'       local.lonlat    local scale longitude and latitude as lon1,lon2,lat1,lat2
#'
#'@import 
#'
#'@return netcdf for the large scale and  netcdf for the local scale
#'        in case you have selected interp=TRUE, netcdf interpolated for the large and local scales
#'      
#'        
#' #'@example
#' large.lonlat="-80,50,22,70 "
#' #local.lonlat="6,20,35,49 " #lon1,lon2,lat1,lat2 #italy
#' local.lonlat="-11,5,34,46 " #lon1,lon2,lat1,lat2 #spain
#' var="slp"
#' directory="~/Downloads/"
#' Namefilein="slp_NCEP_1990-2018_NA"
#' filesmallgrid="prate_ERA5_1990-2018_NA.nc"
#' #by default interpolation=TRUE
#' LargeLocalScale(large.lonlat,local.lonlat,var,Namefilein,directory,interp=TRUE)
#' #just to do an interpolation without selection of regions
#' remapnn(Namefilein,var,filesmallgrid,directory)



# interpolate into a finnest grid using cdo
remapnn<-function(Namefilein,var,filesmallgrid,directory){ 
  fileout=paste(Namefilein,"Interp",sep="")
  system(paste("cd ",directory,"; cdo griddes ",filesmallgrid," > smallgrid.txt",sep=("")))
  system(paste("cd ",directory,"; cdo remapnn,smallgrid.txt ",Namefilein,".nc ",fileout,".nc",sep=("")))
}
# selecting region in cdo to create an netcdf
LargeLocalScale<-function(large.lonlat,local.lonlat,var,Namefilein,directory,interp=TRUE){
    Namefileout.large=paste(var,"Large",sep="")  
    Namefileout.local=paste(var,"Local",sep="")
    system(paste("cd ",directory,"; cdo sellonlatbox,",large.lonlat,Namefilein,".nc ",Namefileout.large,".nc",sep=("")))
    system(paste("cd ",directory,"; cdo sellonlatbox,",local.lonlat,Namefilein,".nc ",Namefileout.local,".nc",sep=("")))
  if(interp==TRUE){
  # interpolate to the nearest neighbor using cdo
  remapnn(Namefileout.large,var,filesmallgrid,directory)
  remapnn(Namefileout.local,var,filesmallgrid,directory)
  }
}    

