
  # -------------------------------------------------------------------------------------------------------------------------  #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                            #
  #           File Name              :  ggDonut.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                                                                                     #
  #                                                                                                                            #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                            #
  #   ggDonut            ( DT, countCol="Count", group="end_reason", byCols=NULL, size=5, thickness=0.65                       #
  #                        , group.nm=group, title="", total=NULL, total.tail="", facetFormula=NULL                            #
  #                        , sortOn=if (is.null(facetFormula)) countCol else group, sortDec=TRUE, cleanTheme=TRUE              #
  #                        , pol.start=pi * 2/3, pol.direction=(-1), anchor=c("largest") )                                     #
  #                                                                                                                            #
  #                                                                                                                            #
  #                                                     <END FUNCS>                                                            #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  # -------------------------------------------------------------------------------------------------------------------------  #

ggDonut <- function(DT, countCol="Count", group="end_reason", byCols=NULL, size=5, thickness=.65, group.nm=group, title="", total=NULL, total.tail="", facetFormula=NULL, sortOn=if(is.null(facetFormula)) countCol else group, sortDec=TRUE, cleanTheme=TRUE, pol.start=pi*2/3, pol.direction=(-1), anchor=c("largest"))  {

  ## TODO:   Anchor is not currently used, but I would like to. 

  if (length(sortOn) > 1)
    stop("sortOn can only have length 1")

  DT <- copy(DT)

  cols <- c(countCol, group, byCols, sortOn)

  ## ERROR CHECK      ##
  if (!nrow(DT))
    stop("DT does not have any rows")
  if (!is.character(cols))
    stop("'countCol', 'group', 'byCols' should all be strings")
  if (identical(sortOn, "perc") && !sortOn %in% names(DT))
    stop("'", sortOn, "' is not a column name. Did you mean to use countCol ('", countCol, "')?")
  if (length(wh <- cols[!(cols %in% names(DT))]))
    stop(warningCols("The following columns are not column names of DT", wh))
  ## ---------------- ##
  

  ## Confirm valid percentage
  thickness <- validPercentage(thickness)

  useTotal <- (isTRUE(total) || identical(total, sum) || identical(total, "sum"))
  if (useTotal) {
    DT.total <- DT[, list(.total=sum(get(countCol), na.rm=TRUE)), by=byCols]
    DT.total[, .total.char := paste0("N = \n", formnumb(.total), if(length(total.tail)) paste0("\n", total.tail))]
  }  ## TODO ##  else if (is.character(total))


  ## Sort rows.  First check for proper input
  if (isTRUE(sortOn))
    sortOn <- group
  if (any(!sortOn %in% names(DT)))
    stop("sortOn must be column name(s) of DT")
  DT[, .ordering := order(get(sortOn), decreasing=sortDec), by=byCols]
  DT <- DT[order(get(sortOn), decreasing=sortDec)]
  ## TODO, allow for sortOn to have length greater than one, once orderch is bugfree
  ##  DT <- DT[orderch(sortOn, decreasing=sortDec)]


  # Calculate plotting points
  DT[, perc := c(perc = get(countCol)/sum(get(countCol))) , by=byCols]
  DT[, perc.ch := fwp(perc)]

  DT[, ymax := cumsum(perc) , by=byCols]
  DT[, ymin := c(0, head(ymax, -1)) , by=byCols]
  DT[, ymid := mean(c(ymax, ymin)), by=list(ymax, ymin)]

  DT[, xmax := size]
  DT[, xmin := size * (1 - thickness)]
  DT[, xmid := ((xmax - xmin) * .4) + xmin]

#  # reorder for centering the plot
#  if (is.factor(DT[[group]]))
#    DT[, c(group) := factor(get(group), levels=shiftb(levels(get(group)), roll=TRUE))]


#  if (missing(pol.start)) {
#    if (length(DT[["perc"]])>1) {
#
#    }
#  }

# browser()
  P <-
   ggplot(DT, aes(start=1)) +
         # Border between sections
         geom_rect(aes_string(ymax="ymax", ymin="ymin", xmax="xmax", xmin="xmin"), color="grey30", show_guides=FALSE) +
         # Actual fill
         geom_rect(aes_string(ymax="ymax", ymin="ymin", xmax="xmax", xmin="xmin", fill=group), show_guide=TRUE) +
         # Label for precentages
         geom_text(aes(y=ymid, x=xmid, label=perc.ch),  size=rel(3.5)) + 
         xlim( c(0, DT[, max(xmax, na.rm=TRUE)]) ) + 
         ylim( c(0, 1)) + 
         labs(title=title, fill=group.nm, x="", y="") +
         coord_polar(theta="y", start=pol.start, direction=pol.direction) 

  if (cleanTheme)
     P <- P + theme_bw() + 
              theme(panel.grid=element_blank()
                  ,  axis.text=element_blank() 
                  , axis.ticks=element_blank())

  if (useTotal)
     P <- P + geom_text(aes(label=.total.char), x=0, y=0, guides=FALSE, size=rel(4), data=DT.total)

  if (is.null(facetFormula) && !is.null(byCols))
     facetFormula <- as.formula(paste0(".~", pasteC(byCols, C="+")))

  if (!(is.null(facetFormula) || identical(facetFormula, FALSE)))
     P <- P + facet_grid(facetFormula)

  P
}
