  # -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  #
  #  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                                                                                                                          #
  #           File Name              :  setPrompt.r                                                                                                                                                                          #
  #           Last Updated Funclist  :  19 Feb 2015, 12:52 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                                                                                                                                                                                   #
  #                                                                                                                                                                                                                          #
  #  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                                                                                                                          #
  #   getGNUScreenName      ( crop=FALSE, pid.included=FALSE, .Pfm=Sys.info()[["sysname"]]                                                                                                                                      #
  #                        , blank=if (.Pfm == "Linux") " no screen " else if (.Pfm == "Darwin") " local OSX " else "" )                                                                                                     #
  #   setPrompt          ( full_screenname=FALSE                                                                                                                                                                             #
  #                        , blank_screenname=ifelse(.Pfm == "Darwin", "local OSX", " no screen "), .Pfm=Sys.info()[["sysname"]]                                                                                             #
  #                        , usingTerm=isTRUE("TERM" %in% names(Sys.getenv()))                                                                                                                                               #
  #                        , usingRevo=any(grepl("Revobase", getOption("defaultPackages"))), usingRStudio=any(grepl("RSTUDIO", names(Sys.getenv()))), usingRGUI=any(grepl("R_GUI_APP", names(Sys.getenv()))), quiet=FALSE )  #
  #                                                                                                                                                                                                                          #
  #                                                                                                                                                                                                                          #
  #                                                                                                    <END FUNCS>                                                                                                           #
  #  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------   #
  # -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  #

getGNUScreenName <- function(crop=FALSE, pid.included=FALSE, .Pfm=Sys.info()[['sysname']], blank=if (.Pfm=="Linux") " no screen " else if (.Pfm=="Darwin") " local OSX " else "") {
## If using GNU Screen, gets the name of the current screen 
## REMINDER TO SELF:  $screen is a variable I have setup in my .bash_profile which is a modification of $STY, a variable created by screen
## TODO:  Bring the logic of STY into R
  screen <- system("echo $screen", TRUE)

  STY   <- system("echo $STY", TRUE)

  # ## in a previous version, I had this.  screen is now STY
  # screen <- ifelse(grepl("^[0-9]+\\.pts", screen)
  #             , yes = substr(screen, 1, regexpr("\\.pts", screen) - 1)
  #             , no  = strsplit(screen, "\\.")[[1]][[2]]
  #            )

  if (grepl("\\.pts", STY)) {
    message("found '.pts' in screen name -- check what you wanted to do with it: '", STY, "'")
    STY <- gsub("\\.pts", "", STY)
  }

  ## Remove the pid, HOWEVER, we want to be sure to leave some indicator of the screen name
  ## Thus, only remove the pid if there is something remaining
  if (!isTRUE(pid.included) && grepl("[A-Za-z]", STY))
    STY <- gsub("^\\d*\\.", "", STY)

  ## create a cropped version. Both will be saved as options
  STY.cropped_name <- ifelse (nchar(STY) <= 9, yes = STY, no = paste0(substr(STY, 1, 3), "..", substr(STY, nchar(STY)-3, nchar(STY))))

  options(screen=STY)
  options(screen.cropped_name=STY.cropped_name)

  if (isTRUE(crop))
    return(STY.cropped_name)
  return(STY)
}


options(prompt.full_screenname=FALSE)
setPrompt <- function(
      full_screenname = getOption("prompt.full_screenname", FALSE)
    , blank_screenname = ifelse(.Pfm == "Darwin", "local OSX", " no screen ")
    , .Pfm         = Sys.info()[['sysname']]
    , usingTerm    = isTRUE("TERM" %in% names(Sys.getenv()))
    , usingRevo    = any(grepl("Revobase", getOption("defaultPackages") ))
    , usingRStudio = any(grepl("RSTUDIO", names(Sys.getenv())))
    , usingRGUI    = any(grepl("R_GUI_APP", names(Sys.getenv())))
    , setTermTab   = TRUE
    , quiet=FALSE
) {
  ## blank_screenname :: What will be used when there is no screen being used.  This can be set to NULL or "" to leave as blank

  ## Indicate to user which distro or app of R the function has interpretted to be running in
  ## 2015-02-10 -- disabling for now, as it has been consistently accurate
  # if (!quiet) 
  #   cat(sprintf("\t\t ------------------------- \n\t\t  running %s in %s \n\t\t -------------------------  \n\n", getOption("Rvendor", "[unknown R distro]"), getOption("Rapp", "[unknown R app]")))

  screen <- getGNUScreenName(crop=(!full_screenname))
  R <- ifelse(usingRevo, "Revo", ifelse(usingTerm, "R", ""))
  PROJ <- if (exists("getProjName")) getProjName(, warnOnBlanks=FALSE) else if (exists("projName")) projName else ""
  SUBPROJ <- if (exists("getProjName")) getProjName(subProj=TRUE, warnOnBlanks=FALSE) else if (exists("projName")) projName else ""
  # OS      <- if (.Pfm == "Linux") else if (.Pfm == "Darwin") "OSX"

  if (is.null(SUBPROJ)) SUBPROJ <- ""

  ## Add something for blanks
  if (!nchar(screen) && !is.null(blank_screenname))
    screen <- blank_screenname

  
  ## Set terminal tab title
  if (isTRUE(setTermTab))
    setTerminalTabTitle()


  options(prompt=paste0({
      ## Screen Text -- dont add the blank screen indicator when in Rapp
      if (nchar(screen) && !(usingRGUI && identical(screen, blank_screenname))) {
        paste0("(",
          screen
          # if (grepl("^[0-9]+\\.pts", screen))
          #   substr(screen, 1, regexpr("\\.pts", screen) - 1)
          # else
          #   strsplit(screen, "\\.")[[1]][[2]]
        , ") ")
      } 
      else
        ""
    },
    ## R/Revo Text
    R, 
    ## Project Text
    {
      if (nchar(PROJ))
          paste0("|", PROJ)
    },
    ## Sub Project Text
    {
      if (nchar(SUBPROJ) && nchar(PROJ))
          paste0(":", SUBPROJ)
    },
    ## Prompt Symbol
    "> "))
  ##  ---  END SET PROMPT  ---  ##
}

getBoxName <- function(short_name=FALSE, .Pfm = Sys.info()[['sysname']]) {
## One can set this function to output whatever machine-name(s) one comonly uses
##    based on whichever identifier makes sense to their working environment

  nm <- switch(.Pfm
          , "Darwin" = "Local OSX"
          , "Linux"   = "AWS"
          ,             "Unknown box"
          )

  if (isTRUE(short_name))
    return(substr(nm, 1, 3))
  else
    return (nm)
}


getPrompt <- function() {
  getOption("prompt")
}


setTerminalTabTitle <- function(title) {
## Sets the title of the tab in iTerm
##
## Default Format for title:
##   {Box Name} | {Screen Name} | {ProjectName} | {SubProjName}


  if (missing(title)) {
    box_name = getBoxName(short=TRUE)
    screen_name = getGNUScreenName()
    proj_name  = getProjName(warnOnBlanks=FALSE)
    subproj_name  = getSubProj(warnOnBlanks=FALSE)

    title <- c(box_name,screen_name,proj_name,subproj_name)
    if (substr(title[[1]], 1, 3) == "Loc" && title[[2]] == "")
      title <- title[-2]
    title <- title[seq(max(1, which(as.logical(nchar(title)))))]
    title <- paste0(title, collapse="|")

    if (title == "Loc")
      title <- "Local"
  }

  cmd <- sprintf('echo -ne "\\033]0;%s\\007"', title)
  system(cmd, intern=TRUE)
  return(invisible(TRUE))
}