# Function to add a mask over the maps 
# July 2016. Veronica Torralba

# Arguments: 
# ~~~~~~~~
# lat:	Array of latitudes.
# lon:	Array of longitudes.
# mask: matrix with dimensions (latitud x longitude).
# dens: the density of shading lines, in lines per inch. The default value of NULL means that no shading lines are drawn. 
#        A zero value of density means no shading nor filling whereas negative values and NA suppress shading (and so allow color filling).
# ang: the slope of shading lines, given as an angle in degrees (counter-clockwise).
# col_line: colour of the lines.
# lwd_size: The line width, a positive number, defaulting to 1. The interpretation is device-specific, and some devices 
#           do not implement line widths less than one. 
# crosshatching: T/F if crosshatching instead of diagonal lines. 

Hatching <- function(lat, lon, mask, dens = 10, ang = 45, col_line = '#252525', 
                     lwd_size = 0.5, crosshatching = FALSE) {
  
  if (length(dim(mask)) != 2){
    stop('The mask matrix should have latitude x longitude dimensions')
  }
  # if (dim(mask)[1] == length(lon) & dim(mask)[2] == length(lat)) {
  #   mask <- t(mask)
  # } else if (dim(mask)[1] != length(lat) | dim(mask)[2] != length(lon)){
  #   stop('The mask matrix should have latitude x longitude dimensions')
  # }
  
  # Calculate cell edges (breaks between lat/lon points)
  get_edges <- function(vec) {
    mid <- diff(vec) / 2
    edges <- c(vec[1] - mid[1], vec[-length(vec)] + mid, vec[length(vec)] + mid[length(mid)])
    return(edges)
  }
  
  x_edges <- get_edges(lon)
  y_edges <- get_edges(lat)
  
  for (i in seq_len(nrow(mask))) {
    for (j in seq_len(ncol(mask))) {
      if (mask[i, j]) {
        x_min <- x_edges[i]
        x_max <- x_edges[i + 1]
        y_min <- y_edges[j]
        y_max <- y_edges[j + 1]
        
        xs <- c(x_min, x_min, x_max, x_max)
        ys <- c(y_min, y_max, y_max, y_min)
        
        polygon(xs, ys, density = dens, angle = ang, border = NA, lwd = lwd_size, col = col_line)
        if (crosshatching) {
          polygon(xs, ys, density = dens, angle = -ang, border = NA, lwd = lwd_size, col = col_line)
        }
      }
    }
  }
}

