#'SMOPGibbsSamplin
#' 
#'@author Paola Marson, \email{paola.marson@meteo.fr}
#'
#'@description takes as input the array of sampling limits and generates a Gibbs Sampling realization of the latent Gaussian Field. 
#'
#'@param i        position of the mesh on which to generate the value of the Guassian Field; 
#'       liminf   array of length the size of the mesh containing the inferior limits for the sampling (managed in the wrap function)
#'       limsup   array of length the size of the mesh containing the superior limits for the sampling
#' 
#'@import 
#'
#'@return numeric the generated value of the Gaussian Field for the point i
#'
#'@example

SMOPGibbsSampling<-function(i, liminf, limsup){    #sample and update
  
  if (sign(liminf[i]) != sign(limsup[i])){    ## normal samp
    
    repeat{
      xx<-rnorm(1,0,1)
      if (liminf[i]<xx & xx< limsup[i]) break
    }
  }
  if (sign(liminf[i])==sign(limsup[i])){                                      ## half normal
    if (limsup[i] ==  Inf){
      if (liminf[i]<0.45){
        repeat{
          xx<-rnorm(1,0,1)
          if (liminf[i]<xx & xx< limsup[i]) break
        }
      }
      if (liminf[i]>0.45){
        repeat{
          xx<-rexp(1,1/liminf[i])
          if (liminf[i]<xx & xx< limsup[i]) break
        }
        
      }                      
    }
    
    
    if (liminf[i] == -Inf){
      if (limsup[i]>(-0.45)){
        repeat{
          xx<-rnorm(1,0,1)
          if (liminf[i]<xx & xx< limsup[i]) break
        }
      }
      if (limsup[i]<(-0.45)){
        repeat{
          xx<-(-1)*rexp(1,-1/limsup[i])
          if(liminf[i]<xx & xx< limsup[i]) break
        }
      }
      
    }
    if (is.finite(liminf[i]) & is.finite(limsup[i])){
      xx<-liminf[i]
      
    }
    
  } 
  
  
  return(hi[i]*xx + sottraendo + MU[i])    
  
}

