PlotEquiMap <- function(var, lon, lat, varu = NULL, varv = NULL,
                        toptitle = NULL, sizetit = 1, units = NULL, 
                        brks = NULL, cols = NULL, colNA = 'white', 
                        square = TRUE, filled.continents = TRUE,
                        coast_color = NULL, coast_width = 1,
                        contours = NULL, brks2 = NULL, 
                        dots = NULL, dot_symbols = '.', dot_sizes = 1, 
                        arr_subsamp = 1, arr_scale = 1, arr_ref_len = 15, 
                        arr_units = "m/s", arr_scale_shaft = 1, 
                        arr_scale_shaft_angle = 1,
                        axelab = TRUE, labW = FALSE, 
                        intylat = 20, intxlon = 20, 
                        drawleg = TRUE, subsampleg = 1,
                        boxlim = NULL, boxcol = 'purple2', boxlwd = 5,
                        numbfig = 1, fileout = NULL, ...) {
  # Process the user graphical parameters that may be passed in the call
  ## Graphical parameters to exclude
  excludedArgs <- c("cex", "cex.axis", "cex.lab", "cex.main", "col", "din", "fig", "fin", "lab", "las", "lty", "lwd", "mai", "mar", "mgp", "new", "oma", "ps", "tck")
  userArgs <- .FilterUserGraphicArgs(excludedArgs, ...)

  # If there is any filenames to store the graphics, process them
  # to select the right device 
  if (!is.null(fileout)) {
    deviceInfo <- .SelectDevice(fileout)
    saveToFile <- deviceInfo$fun
    fileout <- deviceInfo$files
  }

  # Preliminar check of dots, contours, varu, varv, lon, lat
  if (!is.null(dots)) {
    if (!is.array(dots) || !(length(dim(dots)) %in% c(2, 3))) {
      stop("Parameter 'dots' must be a logical array with two or three dimensions.")
    }
    if (length(dim(dots)) == 2) {
      dim(dots) <- c(1, dim(dots))
    }
  }
  if (!is.null(contours)) {
    if (!is.array(contours) || !(length(dim(contours)) == 2)) {
      stop("Parameter 'contours' must be a numerical array with two dimensions.")
    }
  }
  if (!is.null(varu) && !is.null(varv)) {
    if (!is.array(varu) || !(length(dim(varu)) == 2)) {
      stop("Parameter 'varu' must be a numerical array with two dimensions.")
    }
    if (!is.array(varv) || !(length(dim(varv)) == 2)) {
      stop("Parameter 'varv' must be a numerical array with two dimensions.")
    }
  } else if (!is.null(varu) || !is.null(varv)) {
    stop("Only one of the components 'varu' or 'varv' has been provided. Both must be provided.")
  }
  if (!is.numeric(lon) || !is.numeric(lat)) {
    stop("Parameters 'lon' and 'lat' must be numeric vectors.")
  }

  # Check var
  if (!is.array(var)) {
    stop("Parameter 'var' must be a numeric array.")
  }
  if (length(dim(var)) > 2) {
    var <- drop(var)
    dim(var) <- head(c(dim(var), 1, 1), 2)
  }
  if (length(dim(var)) > 2) {
    stop("Parameter 'var' must be a numeric array with two dimensions. See PlotMultiMap() for multi-pannel maps or AnimateMap() for animated maps.")
  } else if (length(dim(var)) < 2) {
    stop("Parameter 'var' must be a numeric array with two dimensions.")
  }
  dims <- dim(var)
  # Transpose the input matrices because the base plot functions work directly 
  # with dimensions c(lon, lat).
  if (dims[1] != length(lon) || dims[2] != length(lat)) {
    if (dims[1] == length(lat) && dims[2] == length(lon)) {
      var <- t(var)
      if (!is.null(varu)) varu <- t(varu)
      if (!is.null(varv)) varv <- t(varv)
      if (!is.null(contours)) contours <- t(contours)
      if (!is.null(dots)) dots <- aperm(dots, c(1, 3, 2))
      dims <- dim(var)
    }
  }

  # Check lon
  if (length(lon) != dims[1]) {
    stop("Parameter 'lon' must have as many elements as the number of cells along longitudes in the input array 'var'.")
  }

  # Check lat
  if (length(lat) != dims[2]) {
    stop("Parameter 'lat' must have as many elements as the number of cells along longitudes in the input array 'var'.")
  }

  # Check varu and varv
  if (!is.null(varu) && !is.null(varv)) {
    if (dim(varu)[1] != dims[1] || dim(varu)[2] != dims[2]) {
      stop("Parameter 'varu' must have same number of longitudes and latitudes as 'var'.")
    }
    if (dim(varv)[1] != dims[1] || dim(varv)[2] != dims[2]) {
      stop("Parameter 'varv' must have same number of longitudes and latitudes as 'var'.")
    }
    if (drawleg == TRUE) {
      stop("Plotting arrows (via 'varu' and 'varv') is not compatible with 'drawleg = TRUE'.")
    } else if (square == FALSE) {
      stop("Plotting arrows (via 'varu' and 'varv') is only possible if 'square = TRUE'.")
    }
  }

  # Check toptitle
  if (is.null(toptitle)) {
    toptitle <- ''
  }
  if (!is.character(toptitle)) {
    stop("Parameter 'toptitle' must be a character string.")
  }

  # Check sizetit
  if (!is.numeric(sizetit) || length(sizetit) != 1) {
    stop("Parameter 'sizetit' must be a single numeric value.")
  }

  # Check units
  if (is.null(units)) {
    units <- ''
  }
  if (!is.character(units)) {
    stop("Parameter 'units' must be a character string.")
  }

  # Check brks and cols
  varlim <- signif(c(min(var, na.rm = TRUE), max(var, na.rm = TRUE)), 4)
  if (!is.null(cols)) {
    if (!is.character(cols)) {
      stop("Parameter 'cols' must be a character vector.")
    }
  }
  if (is.null(brks)) {
    if (!is.null(cols)) {
      brks <- length(cols) + 1
    } else {
      brks <- 21
    }
  }
  if (is.numeric(brks)) {
    if (length(brks) == 1) {
      brks <- seq(varlim[1], varlim[2], length.out = brks)
    }
    if (is.null(cols)) {
      cols <- clim.colors(length(brks) - 1)
    } else if (length(cols) != (length(brks) - 1)) {
      stop("Inconsistent number of 'brks' and 'cols'. There must be one more break than the number of colours.")
    }
  } else {
    stop("Parameter 'brks' must be a numeric vector.")
  }

  # Check colNA
  if (!is.character(colNA)) {
    stop("Parameter 'colNA' must be a character string.")
  }

  # Check square
  if (!is.logical(square)) {
    stop("Parameter 'square' must be logical.")
  }

  # Check filled.continents
  if (!.IsColor(filled.continents) && !is.logical(filled.continents)) {
    stop("Parameter 'filled.continents' must be logical or a colour identifier.")
  } else if (!is.logical(filled.continents)) {
    continent_color <- filled.continents
    filled.continents <- TRUE
  } else if (filled.continents) {
    continent_color <- gray(0.5)
  }

  # Check coast_color
  if (is.null(coast_color)) {
    if (filled.continents) {
      coast_color <- continent_color
    } else {
      coast_color <- 'black'
    }
  }
  if (!.IsColor(coast_color)) {
    stop("Parameter 'coast_color' must be a valid colour identifier.")
  }

  # Check coast_width
  if (!is.numeric(coast_width)) {
    stop("Parameter 'coast_width' must be numeric.")
  }

  # Check contours
  if (!is.null(contours)) {
    if (dim(contours)[1] != dims[1] || dim(contours[2]) != dims[2]) {
      stop("Parameter 'contours' must have the same number of longitudes and latitudes as 'var'.")
    }
  }

  # Check brks2
  if (is.null(brks2)) {
    if (is.null(contours)) { 
      if (!square) {
        brks2 <- brks
        contours <- var 
      }
    } else {
      ll <- signif(min(contours, na.rm = TRUE), 2)
      ul <- signif(max(contours, na.rm = TRUE), 2)
      brks2 <- signif(seq(ll, ul, length.out = length(brks)), 2)
    }
  }

  # Check dots, dot_symbols and dot_sizes
  if (!is.null(dots)) {
    if (dim(dots)[2] != dims[1] || dim(dots)[3] != dims[2]) {
      stop("Parameter 'dots' must have the same number of longitudes and latitudes as 'var'.")
    }
    if (is.null(dot_symbols)) {
      dot_symbols <- c('.', '/', '*', 'o', 'x', 1:(dim(dots)[1] - 5))
    } else if (length(dot_symbols) == 1) {
      dot_symbols <- rep(dot_symbols, dim(dots)[1])
    } else if (length(dot_symbols) < dim(dots)[1]) {
      stop("Parameter 'dot_symbols' does not contain enough symbols.")
    }
    if (is.null(dot_sizes)) {
      dot_sizes <- rep(1, dim(dots)[1])
    } else if (length(dot_sizes) == 1) {
      dot_sizes <- rep(dot_sizes, length(dot_sizes))
    } else if (length(dot_sizes) < dim(dots)[1]) {
      stop("Parameter 'dot_sizes' does not contain enough sizes.")
    }
  }

  # Check arrow parameters
  if (!is.numeric(arr_subsamp)) {
    stop("Parameter 'arr_subsamp' must be numeric.")
  }
  if (!is.numeric(arr_scale)) {
    stop("Parameter 'arr_scale' must be numeric.")
  }
  if (!is.numeric(arr_ref_len)) {
    stop("Parameter 'arr_ref_len' must be numeric.")
  }
  if (!is.character(arr_units)) {
    stop("Parameter 'arr_units' must be character.")
  }
  if (!is.numeric(arr_scale_shaft)) {
    stop("Parameter 'arr_scale_shaft' must be numeric.")
  }
  if (!is.numeric(arr_scale_shaft_angle)) {
    stop("Parameter 'arr_scale_shaft_angle' must be numeric.")
  }

  # Check axis parameters
  if (!is.logical(axelab)) {
    stop("Parameter 'axelab' must be logical.")
  }
  if (!is.logical(labW)) {
    stop("Parameter 'labW' must be logical.")
  }
  if (!is.numeric(intylat)) {
    stop("Parameter 'intylat' must be numeric.")
  } else {
    intylat <- round(intylat)
  }
  if (!is.numeric(intxlon)) {
    stop("Parameter 'intxlon' must be numeric.")
  } else {
    intxlon <- round(intxlon)
  }

  # Check legend parameters
  if (!is.logical(drawleg)) {
    stop("Parameter 'drawleg' must be logical.")
  }
  if (!is.numeric(subsampleg)) {
    stop("Parameter 'subsampleg' must be numeric.")
  } else {
    subsampleg <- round(subsampleg)
  }

  # Check box parameters
  if (!is.null(boxlim)) {
    if (!is.list(boxlim)) {
      boxlim <- list(boxlim)
    }
    for (i in 1:length(boxlim)) {
      if (!is.numeric(boxlim[[i]]) || length(boxlim[[i]]) != 4) {
        stop("Parameter 'boxlim' must be a a numeric vector or a list of numeric vectors of length 4 (with W, S, E, N box limits).")
      }
    }
    if (!is.character(boxcol)) {
      stop("Parameter 'boxcol' must be a character string or a vector of character strings.")
    } else {
      if (length(boxlim) != length(boxcol)) {
        if (length(boxcol) == 1) {
          boxcol <- rep(boxcol, length(boxlim))
        } else {
          stop("Parameter 'boxcol' must have a colour for each box in 'boxlim' or a single colour for all boxes.")
        }
      }
    }
    if (!is.numeric(boxlwd)) {
      stop("Parameter 'boxlwd' must be numeric.")
    } else {
      if (length(boxlim) != length(boxlwd)) {
        if (length(boxlwd) == 1) {
          boxlwd <- rep(boxlwd, length(boxlim))
        } else {
          stop("Parameter 'boxlwd' must have a line width for each box in 'boxlim' or a single line width for all boxes.")
        }
      }
    }
  }

  # Check numbfig
  if (!is.numeric(numbfig)) {
    stop("Parameter 'numbfig' must be numeric.")
  } else {
    numbfig <- round(numbfig)
  }

  #library(GEOmap)
  #library(geomapdata)
  #library(maps)
  data(coastmap, package = 'GEOmap', envir = environment())
  #
  #  Input arguments 
  # ~~~~~~~~~~~~~~~~~
  #
 
  latb <- sort(lat, index.return = TRUE)
  dlon <- lon[2:dims[1]] - lon[1:(dims[1] - 1)]
  wher <- which(dlon > (mean(dlon) + 1))
  if (length(wher) > 0) {
    lon[(wher + 1):dims[1]] <- lon[(wher + 1):dims[1]] - 360
  }
  lonb <- sort(lon, index.return = TRUE)
  latmin <- floor(min(lat) / 10) * 10
  latmax <- ceiling(max(lat) / 10) * 10
  lonmin <- floor(min(lon) / 10) * 10
  lonmax <- ceiling(max(lon) / 10) * 10

  #
  #  Plotting the map
  # ~~~~~~~~~~~~~~~~~~
  #

  # Open connection to graphical device
  if (!is.null(fileout)) saveToFile(fileout, width = 11, height = 8)
  # Load the user parameters
  par(userArgs)

  if (axelab == TRUE) { 
    ypos <- seq(latmin, latmax, intylat)
    xpos <- seq(lonmin, lonmax, intxlon)
    letters <- array('', length(ypos))
    letters[ypos < 0] <- 'S'
    letters[ypos > 0] <- 'N'
    ylabs <- paste(as.character(abs(ypos)), letters, sep = '')
    letters <- array('', length(xpos))
    if (labW) {
      nlon <- length(xpos)
      xpos2 <- xpos  
      xpos2[xpos2 > 180] <- 360 - xpos2[xpos2 > 180]
    }
    letters[xpos < 0] <- 'W'
    letters[xpos > 0] <- 'E'
    if (labW) {
      letters[xpos == 0] <- ' '
      letters[xpos == 180] <- ' '
      letters[xpos > 180] <- 'W'  
      xlabs <- paste(as.character(abs(xpos2)), letters, sep = '')
    } 
    else{
      xlabs <- paste(as.character(abs(xpos)), letters, sep = '')
    }
    xmargin <- 1.2 - (numbfig ^ 0.2) * 0.05
    ymargin <- 3 - (numbfig ^ 0.2)
    spaceticklab <- 1.3 - (numbfig ^ 0.2) * 0.8
    topmargin <- 0.4
    ymargin2 <- 1.8 - (numbfig ^ 0.2) * 0.9
  } else {
    xmargin <- 0.2 
    ymargin <- 0.2 + switch(as.character(square), 'FALSE' = 1.8, 0) 
    topmargin <- 0.2
    spaceticklab <- 1
    ymargin2 <- 0.2
  }
  if (!is.null(toptitle)) {
    if (!is.na(toptitle) && is.character(toptitle)) {
      if (toptitle != '') {
        topmargin <- 2.5 - (numbfig ^ 0.2) * 0.6
      }
    }
  }
  if (min(lon) < 0) {
    continents <- 'world'
  } else {
    continents <- 'world2'
  }
  # Increase the bottom margin
  # to plot the legend of the arrow plot
  if (!is.null(varu)) {
    if (!axelab){
      xmargin <- xmargin + 2.5 / numbfig #(numbfig^(0.3))
    } else {
      xmargin <- xmargin + xmargin / numbfig #(numbfig^(0.3))
    }
  }

  if (square) {
    if (drawleg) {
      layout(matrix(1:2, ncol = 1, nrow = 2), heights = c(5, 1))
    }
    par(mar = c(xmargin, ymargin, topmargin, ymargin2), cex = 1.4, 
        mgp = c(3, spaceticklab, 0), las = 0)
    if (colNA != 'white') {
      blanks <- array(0, dim = c(length(lonb$x), length(latb$x)))
      image(lonb$x, latb$x, blanks, col = c(colNA), breaks = c(-1, 1), 
            main = toptitle, cex.main = (1.5 / numbfig ^ (0.2)) * sizetit, 
            axes = FALSE, xlab = "", ylab = "")
      flagadd <- T
    } else {  
      flagadd <- F
    }
    image(lonb$x, latb$x, var[lonb$ix, latb$ix], col = cols, breaks = brks, 
          main = toptitle, axes = FALSE, xlab = "", ylab = "", 
          cex.main = (1.5 / numbfig ^ (0.2)) * sizetit, add = flagadd)
    if (axelab == TRUE) {
      axis(2, at = ypos, labels = ylabs, cex.axis = 1 / (numbfig ^ 0.3), 
           tck = -0.03)
      axis(1, at = xpos, labels = xlabs, cex.axis = 1 / (numbfig ^ 0.3),
           tck = -0.03)
    }
    if (is.null(contours) == FALSE) {
      contour(lonb$x, latb$x, contours[lonb$ix, latb$ix], levels = brks2,
              method = "edge", add = TRUE, labcex = 1 / numbfig, 
              lwd = 0.5 / (numbfig ^ 0.5))
    }
    #map(continents, interior = FALSE, add = TRUE, lwd = 1, resolution = 0)
    box()
  } else {
    par(mar = c(xmargin + 5, ymargin + 1.5, topmargin, ymargin2), 
        cex.main = (1.6 * numbfig ^ (0.3)) * sizetit, cex.axis = 1.4, 
        cex.lab = 1.6, mgp = c(3, spaceticklab + 0.5, 0), las = 0)
    if (axelab == TRUE) {
      filled.contour(lonb$x, latb$x, var[lonb$ix, latb$ix], xlab = "", 
                     levels = brks, col = cols, ylab = "", main = toptitle,
                     key.axes = axis(4, brks[seq(1, length(brks), subsampleg)],
                     cex.axis = 1 / (numbfig ^ 0.3)), 
                     plot.axes = {axis(2, at = ypos, labels = ylabs, 
                                  cex.axis = 1 / (numbfig ^ 0.3), tck = -0.03)
                                  axis(1, at = xpos, labels = xlabs,
                                  cex.axis = 1 / (numbfig ^ 0.3), tck = -0.03)
                                  contour(lonb$x, latb$x, contours[lonb$ix,
                                          latb$ix], levels = brks2, 
                                          method = "edge", add = TRUE,
                                          labcex = 1, lwd = 2)
                                  map(continents, interior = FALSE, 
                                      xlim = c(lonmin, lonmax),
                                      ylim = c(latmin, latmax), add = TRUE,
                                      resolution = 0)},
                     key.title = title(main = units, 
                                 cex.main = (1.2 * numbfig ^ (0.3)) * sizetit))
    } else {
      filled.contour(lonb$x, latb$x, var[lonb$ix, latb$ix], xlab = "",
                     levels = brks, col = cols, ylab = "", main = toptitle,
                     key.axes = axis(4, brks[seq(1, length(brks), subsampleg)],
                     cex.axis = 1 / (numbfig ^ 0.3)), 
                     plot.axes = {contour(lonb$x, latb$x, contours[lonb$ix, 
                                          latb$ix], levels = brks2, 
                                          method = "edge", add = TRUE,
                                          labcex = 1, lwd = 2)
                                  map(continents, interior = FALSE, 
                                      xlim = c(lonmin, lonmax), 
                                      ylim = c(latmin, latmax), add = TRUE,
                                      resolution = 0)},
                     key.title = title(main = units, 
                                 cex.main = (1.2 * numbfig ^ (0.3)) * sizetit))
    }
  } 
  #
  #  Adding black dots or symbols
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  #
  if (!is.null(dots)) {
    plot_dot <- function(x, y, symbol, size) {
      text(x = x, y = y, symbol,
           cex = size * 12 / (sqrt(sqrt(length(var))) * numbfig ^ 0.5))
    }
    plot_dots <- Vectorize(plot_dot, vectorize.args = c('x', 'y'))
    data_avail <- !is.na(var)
    for (counter in 1:(dim(dots)[1])) {
      points <- which(dots[counter, , ] & data_avail, arr.ind = TRUE)
      plot_dots(lon[points[, 1]], lat[points[, 2]], 
                dot_symbols[counter], dot_sizes[counter])
    }
  }
  #
  #  Plotting continents
  # ~~~~~~~~~~~~~~~~~~~~~
  # 
  if (square) {
    coast <- map(continents, interior = FALSE, wrap = TRUE,
                 fill = filled.continents, add = TRUE, plot = FALSE)
    if (filled.continents) {
      old_lwd <- par('lwd')
      par(lwd = coast_width)
      if (min(lon) >= 0) {
        ylat <- latmin:latmax
        xlon <- lonmin:lonmax
        proj <- GEOmap::setPROJ(1, LON0 = mean(xlon),
                                LAT0 = mean(ylat), LATS = ylat, LONS = xlon)
        lakes <- which(coastmap$STROKES$col == "blue")
        coastmap$STROKES$col[which(coastmap$STROKES$col != "blue")] <- continent_color
        coastmap$STROKES$col[lakes] <- "white"
        par(new = TRUE)
        GEOmap::plotGEOmap(coastmap, PROJ = proj, border = coast_color, 
                           add = TRUE, lwd = coast_width)
      } else {
        polygon(coast, col = continent_color, border = coast_color, lwd = coast_width)
      }
      par(lwd = old_lwd)
    } else {
      lines(coast, col = coast_color, lwd = coast_width)
    }
    box()
  }
  # Draw rectangle on the map
  if (!is.null(boxlim)) {
    counter <- 1
    for (box in boxlim) {
      if (box[1] > box[3]) {
        box[1] <- box[1] - 360
      }
      if (length(box) != 4) {
        stop(paste("The", counter, "st box defined in the parameter 'boxlim' is ill defined."))
      } else if (box[2] < latmin || box[4] > latmax || 
                 box[1] < lonmin || box[3] > lonmax) {
        stop(paste("The limits of the", counter, "st box defined in the parameter 'boxlim' are invalid."))
      } else if (box[1] < 0 && box[3] > 0) {
        #segments south
        segments(box[1], box[2], 0, box[2], col = boxcol[counter], lwd = boxlwd[counter])
        segments(0, box[2], box[3], box[2], col = boxcol[counter], lwd = boxlwd[counter]) 
        #segments north
        segments(box[1], box[4], 0, box[4], col = boxcol[counter], lwd = boxlwd[counter])
        segments(0, box[4], box[3], box[4], col = boxcol[counter], lwd = boxlwd[counter]) 
        #segments west
        segments(box[1], box[2], box[1], box[4], col = boxcol[counter], 
                 lwd = boxlwd[counter])  
        #segments est
        segments(box[3], box[2], box[3],box[4], col = boxcol[counter], 
                 lwd = boxlwd[counter])          
      } else {
        rect(box[1], box[2], box[3], box[4], border = boxcol[counter], col = NULL, 
             lwd = boxlwd[counter], lty = 'solid')
      }
      counter <- counter + 1
    }
  }
  #
  #  PlotWind
  # ~~~~~~~~~~
  #
  if (!is.null(varu) && !is.null(varv)) {
    # Create a two dimention array of longitude and latitude
    lontab <- InsertDim(lonb$x, 2, length( latb$x))
    lattab <- InsertDim(latb$x, 1, length( lonb$x))
    varplotu <- varu[lonb$ix, latb$ix]
    varplotv <- varv[lonb$ix, latb$ix]

    # Select a subsample af the points to an arrow
    #for each "subsample" grid point
    sublon <- seq(1,length(lon), arr_subsamp)
    sublat <- seq(1,length(lat), arr_subsamp)

    uaux <- lontab[sublon, sublat] + varplotu[sublon, sublat] * 0.5 * arr_scale
    vaux <- lattab[sublon, sublat] + varplotv[sublon, sublat] * 0.5 * arr_scale

    lenshaft <- 0.18 * arr_scale * arr_scale_shaft / (numbfig ^ (0.2))
    angleshaft <- 12 * arr_scale_shaft_angle / (numbfig ^ (0.2))
    # Plot Wind
    arrows(lontab[sublon, sublat], lattab[sublon, sublat],
           uaux, vaux,
           angle = angleshaft,
           length = lenshaft)

    # Plotting an arrow at the bottom of the plot for the legend
    posarlon = lonb$x[1] + (lonmax - lonmin) * 0.1
    posarlat = latmin - (latmax - latmin) * 0.035

    arrows(posarlon, posarlat,
           posarlon + 0.5 * arr_scale * arr_ref_len, posarlat,
           length = lenshaft, angle = angleshaft,
           xpd = TRUE)
    #save the parameter value
    xpdsave = par()$xpd
    #desactivate xpd to be able to plot in margen
    par(xpd = NA)
    #plot text
    text(x = posarlon + arr_scale, y = posarlat - (latmax - latmin) * 0.03,
         labels = paste(as.character(arr_ref_len), arr_units, sep = ""),
         cex = (1 * sizetit / numbfig ^ (0.2)) )
    #come back to the previous xpd value
    par(xpd = xpdsave)
  }
  #
  #  Colorbar
  # ~~~~~~~~~~
  #
  if (square && drawleg) {
    par(mar = c(1.5, ymargin + 1.5, 2.5, ymargin2 + 1.5), mgp = c(1.5, 0.3, 0), 
        las = 1, cex = 1.2)
    image(1:length(cols), 1, t(t(1:length(cols))), axes = FALSE, col = cols, 
          xlab = '', ylab = '', main = units, cex.main = 1.1)
    box()
    axis(1, at = seq(0.5, length(brks) - 0.5, subsampleg), 
         labels = brks[seq(1, length(brks), subsampleg)])
    #title(xlab = units)
  }

  # If the graphic was saved to file, close the connection with the device
  if (!is.null(fileout)) dev.off()

  invisible(list(cols = cols, brks = brks))
}
