
  # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  #
  #  ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                                                                                         #
  #           File Name              :  detlaCut.r                                                                                                                                          #
  #           Last Updated Funclist  :  08 Feb 2015,  5:14 AM (Sunday)                                                                                                                      #
  #                                                                                                                                                                                         #
  #           Author Name            :  Rick Saporta                                                                                                                                        #
  #           Author Email           :  RickSaporta@gmail.com                                                                                                                               #
  #           Author URL             :  www.github.com/rsaporta                                                                                                                             #
  #                                                                                                                                                                                         #
  #           Packages Called        :  NA                                                                                                                                                  #
  #           Packages Used via NS   :  NA                                                                                                                                                  #
  #                                                                                                                                                                                         #
  #  ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                                                                                         #
  #   deltaCut_          ( DT                                                                                                                                                               #
  #                        , colToCut, cuts=c(0.005, 0.1, 2.5, 20)/100, distanceFrom=c(1, 0), bottom=ifelse(identical(distanceFrom, 0), -Inf, 0), top=c(Inf, 100, NULL), newCol="accuracy"  #
  #                        , deltaSymbol="Δ", cropMax=FALSE, overwrite_the_column=FALSE, tol.max=1e-10 )                                                                                    #
  #                                                                                                                                                                                         #
  #                                                                                                                                                                                         #
  #                                                                                    <END FUNCS>                                                                                          #
  #  ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------   #
  # --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  #

deltaCut_ <- function(
    DT
  , colToCut
  , cuts = c(.005, .1, 2.5, 20) / 100
  , distanceFrom = c(1, 0)
  , bottom = ifelse(identical(distanceFrom, 0), -Inf, 0)
  , top = c(Inf, 100, NULL)
  , newCol = "accuracy"
  , deltaSymbol = "Δ"
  , cropMax = FALSE
  , overwrite_the_column = FALSE
  , tol.max = 1e-10
) {


  distanceFrom <- distanceFrom[[1]]
  bottom <- bottom[[1]]
  top    <- top[[1]]

  DT[ , .delta. := abs(get(colToCut) - distanceFrom)]
  #---------

  ## Confirm distance from is a finite number
  stopifnot(is.numeric(distanceFrom) && is.finite(distanceFrom))
  ## Confirm cuts are numeric and sorted
  stopifnot(is.numeric(cuts))
  stopifnot(identical(cuts, sort(cuts)))

  if (is.null(bottom)) {
    bottom <- cuts[[1]]
    cuts <- cuts[-1]
  }
  stopifnot(bottom <= cuts[[1]])
  if (bottom == cuts[[1]])
    warning ("bottom is the same as the first element in cuts. This will check for exactly that value.\nHINT: did you mean to set bottom = NULL ?")
  if (any(duplicated(cuts)))
    warning ("There are duplicate values in cuts. This will check for exactly that value.")

  if (newCol %in% names(DT)) {
    err.msg <- sprintf("'%s' already exists in %s", newCol, capture.output(substitute(DT)))
    if (!isTRUE(overwrite_the_column))
      stop (err.msg, "\nHINT: use overwrite_the_column=TRUE to replace")
    warning (err.msg, " \nIt will be overwritten", call.=FALSE)
    DT[, (newCol) := NULL]
  }

  
  ## initialize
  DT[, (newCol) := NA_integer_]
  labs <- character()
  levs <- seq(c(cuts, top))
  minb <- bottom

  for (i in levs) {
    maxb <- c(cuts, Inf)[i]  - tol.max

    # if (i == 1) {
    #   if (is.null(bottom)) {
    #     message("skipping i==1 because 'bottom' is NULL")
    #     next;
    #   } else {
    #     minb <- NULL
    #   }
    # }
    cat(i, ": ")

    DT[ minb <= .delta. & .delta. < maxb, (newCol) := i]
    (str_min <- if(!is.null(minb) && is.finite(minb)) sprintf("%6s <= ", fwp(minb, 3, "", zero=FALSE)) else "")
    (str_max <- if(!is.null(maxb) && is.finite(maxb)) sprintf(  " < %s", fwp(maxb, 3, "", zero=FALSE)) else "")
    labs[[i]] <- (sprintf("%s%s%s", str_min, deltaSymbol, str_max))
    cat(labs[[i]], "\n")
    minb <- maxb
  }
 
  if (isTRUE(cropMax)) {
    maxb <- max(cuts)
    DT[ , ".col_was_cropped" := .delta. > maxb & !is.na(.delta.)]
    DT[(.col_was_cropped), (colToCut) := distanceFrom + (maxb * sign(get(colToCut) - distanceFrom))]
  }

  ## Convert to Factor
  DT[, (newCol) := factor(get(newCol), labels=labs, levels=levs)]

  ## Cleanup
  DT[, .delta. := NULL]
  rm(minb, maxb, labs, levs)
  return(invisible(DT))
}
