  # -------------------------------------------------------------------------------------------------------------------------  #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                            #
  #           File Name              :  facet_colors.r                                                                         #
  #           Last Updated Funclist  :  19 Feb 2015,  1:05 PM (Thursday)                                                       #
  #                                                                                                                            #
  #           Author Name            :  Rick Saporta                                                                           #
  #           Author Email           :  RickSaporta@gmail.com                                                                  #
  #           Author URL             :  www.github.com/rsaporta                                                                #
  #                                                                                                                            #
  #           Packages Called        :  NA                                                                                     #
  #           Packages Used via NS   :  NA                                                                                     #
  #                                                                                                                            #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                            #
  #   get_grob_strips    ( G, strips=grep(pattern="strip.*", G$layout$name) )                                                  #
  #   refill             ( strip, colour )                                                                                     #
  #   colorByGroup       ( P, colors, showWarnings=TRUE )                                                                      #
  #                                                                                                                            #
  #                                                                                                                            #
  #                                                     <END FUNCS>                                                            #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  # -------------------------------------------------------------------------------------------------------------------------  #

get_grob_strips <- function(G, strips=grep(pattern="strip.*", G$layout$name)) {
## Returns a key-value, where the key is the strip-type  (ie strip-top, strip-right, etc)
##   and the value is the label to that strip

  if (inherits(G, "gg"))
    G <- ggplotGrob(G)
  if (!inherits(G, "gtable"))
    stop ("G must be a gtable object or a gg object")


  strip.type <- G$layout[strips, "name"]

  ## This sometimes work  
  strip.nms <- sapply(strips, function(i) {
     tryCatch(attributes(G$grobs[[i]]$width$arg1)$data[[1]][["label"]], error=function(e) NULL)
  })

  ## If the above doesn't work, try the following
  if (!length(removeNullsFromList(strip.nms)))
  strip.nms <- sapply(strips, function(i) {
     tryCatch(attributes(G$grobs[[i]]$width)$data[[1]]$children[[1]][["label"]], error=function(e) NULL)
  })


  data.table(grob_index=strips, type=strip.type, group=strip.nms)
}


refill <- function(strip, colour){
  strip[["children"]][[1]][["gp"]][["fill"]] <- colour
  return(strip)
}

colorByGroup <- function(P, colors, showWarnings=TRUE) {
## The names of colors should match to the groups in facet
  G <- ggplotGrob(P)
  DT.strips <- get_grob_strips(G)

  groups <- names(colors)
  if (is.null(groups) || !is.character(groups)) {
    groups <- unique(DT.strips$group)
    if (length(colors) < length(groups))
      stop ("not enough colors specified")
    colors <- colors[seq(groups)]
    names(colors) <- groups
  }


  ## 'groups' should match the 'group' in DT.strips, which came from the facet_name
  matched_groups <- intersect(groups, DT.strips$group)
  if (!length(matched_groups))
    stop ("no groups match")
  if (showWarnings) {
      if (length(wh <- setdiff(groups, DT.strips$group)))
        warning ("values in 'groups' but not a facet label: \n", paste(wh, colapse=", "))
      if (length(wh <- setdiff(DT.strips$group, groups)))
        warning ("values in facet label but not in 'groups': \n", paste(wh, colapse=", "))
  }

  ## identify the indecies to the grob and the appropriate color
  DT.strips[, color := colors[group]]
  inds <- DT.strips[!is.na(color), grob_index]
  cols <- DT.strips[!is.na(color), color]

  ## Fill in the appropriate colors, using refill()
  G$grobs[inds] <- mapply(refill, strip = G$grobs[inds], colour = cols, SIMPLIFY = FALSE)

  G
}

