#'Grid to Grids Proximity
#'
#'@author Paola Marson, \email{paola.marson@cmcc.it} \email{paola.marson@gmail.com}
#'@description Given a reference grid, this function finds for each of its spatial point the closest point of an arbitrary number of a secondary grid.
#'
#'@param mesh reference mesh of the analysis. A list of length 2 with longitudes and latitudes
#'
#'@param grids list of arbitrary length of secondary grids. Each secondary grid is to be provided as a list of length 2 with longitudes and latitudes 
#'
#'@return a list of same length of \code{grids}. Each element is a list of length 2 containing the indexes of longitudes and latitudes of the closest point to each reference point. 
#'
#'@import s2dverification, fields, geosphere
#'
#'@examples
#'# Creating an example of reference mesh:
#'mesh<-list(1:5, 31:35)
#'# Creating an example of 2 secondary grid:
#'y<-list(seq(1,5,0.5), seq(21,25,0.5))
#'x<-list(1:5, 36:40)
#'grids<-list(y = y,x = x)
#'igrids<-Grid2GridProximity(mesh,grids) 
#'str(igrids)
#'#List of 2
#'# $ y:List of 2
#'#  ..$ ilon: int [1:25(1d)] 1 3 5 7 9 1 3 5 7 9 ...
#'#  ..$ ilat: int [1:25(1d)] 9 9 9 9 9 9 9 9 9 9 ...
#'# $ x:List of 2
#'#  ..$ ilon: int [1:25(1d)] 1 2 3 4 5 1 2 3 4 5 ...
#'#  ..$ ilat: int [1:25(1d)] 1 1 1 1 1 1 1 1 1 1 ...

 
Grid2GridProximity <- function(mesh, grids){

proxy.f<-function(y){
   yy<-expand.grid(y)
   d<-distm(x=mesh, y=yy, fun=distHaversine)
   w.min<-apply(d,1,which.min)
   ilon<-ilat<-array(dim=length(w.min))
   for (i in 1:length(w.min)){
       ilon[i]<-which(y[[1]] == yy[w.min[i],1])
       ilat[i]<-which(y[[2]] == yy[w.min[i],2])
   }
return(list(ilon=ilon,ilat=ilat)) 
}

mesh<-expand.grid(mesh[[1]],mesh[[2]])
name<-names(grids)

igrids=lapply(grids,proxy.f)
names(igrids)<-names(grids)

return(igrids)
}
