.setSFsysvars_ifblank <- function() {
## Sets environmental variables for snowflake

  if (.Pfm == "Darwin")
    return(NULL)

  setSysVarIfBlank("LD_LIBRARY_PATH",  "/usr/lib64/R/lib:/usr/local/lib64:/usr/lib/jvm/jre/lib/amd64/server:/usr/lib/jvm/jre/lib/amd64:/usr/lib/jvm/java/lib/amd64:/usr/java/packages/lib/amd64:/lib:/usr/lib::/etc/snowflake/snowflake_odbc:/usr/bin/snowflake_odbc/lib")
  setSysVarIfBlank("ODBCSYSINI",  "/usr/bin/snowflake_odbc/conf")
  setSysVarIfBlank("SIMBAINI",  "/usr/bin/snowflake_odbc/conf/unixodbc.snowflake.ini")

  options(snowflake_sysvars_set=TRUE)
}

odbcDriverConnect_wrapper <- function(dsn=getOption("snowflake_driver"), uid=getOption("snowflake_uid"), pwd=getOption("snowflake_pwd"), ...) {
## use this function instead of odbcConnect(), since this allows for Warehouse, database and other arguments
  ARGS <- collectArgs() %>% {.[!sapply(., function(x) !length(x) || !nchar(x))]}

  ## check for some standard names
  nms <- names(ARGS) %>% tolower
  names(ARGS)[nms == "wh"] <- "warehouse"
  names(ARGS)[nms %in% c("dbname", "db")] <- "database"

  ## Make names uppercase
  names(ARGS) <- toupper(names(ARGS))

  sprintf("%s=%s", names(ARGS), ARGS) %>% pasteC(C=";") %>% as.list() %>%
    do.call(RODBC::odbcDriverConnect, .)
}


sfGetCon <- function(
      uid=getOption("snowflake_uid")
    , pwd=getOption("snowflake_pwd")
    , drv=getOption("snowflake_driver", "SnowflakeDSII")
    , wh=getSnowflakeWH(refresh=FALSE)
    , dbname=getSnowflakeDB(refresh=FALSE)
    , schema=getSnowflakeSchema(refresh=FALSE)
    , assign=TRUE, envir=.get_sfEnvir()
    , tracing=getOption("snowflake_tracing", 0)
    , refresh=NULL
    , set_snowflake_inuse=TRUE
    , set_defaults=!missing(wh) || !missing(dbname) || !missing(schema)
    , quiet_connex=isTRUE(getOption("sfGetCon_quiet_connex"))
) {

  ## SET SYS VARS IF NOT PREVIOUSLY SET
  if (!getOption("snowflake_sysvars_set", default=FALSE))
    .setSFsysvars_ifblank()

  ## Collect these one time, used often in do.call
  args_for_drv <- list(dsn=drv, uid=uid, pwd=pwd, warehouse=wh, database=dbname, schema=schema, tracing=tracing)

  if (is.null(drv))
    stop ("drv cannot be NULL.\n\nHINT: run   setSnowflakeOptions()")

  if (isTRUE(set_snowflake_inuse))
    options("snowflake_inuse" = TRUE)

  if (!.is_RODBC_loaded()) {
    refresh <- TRUE
    .DBlib("snowflake")
  }

  if (!isTRUE(refresh) && exists(".sfcon", envir=envir, inherits=FALSE, mode="numeric")) {
    .sfcon <- get(".sfcon", envir=envir)
    # if (isConExpired(.sfcon)) {
    #   cat("expired - trying to reconnect ... ")
    #   assign(".sfcon", odbcReConnect(channel=.sfcon), envir=envir)
    #   .sfcon <- get(".sfcon", envir=envir)
    #   cat(ifelse(isConExpired(.sfcon), " FAILED :(", "Success!"), "\n")
    # }
    if (!isConExpired(.sfcon)) {
      # if (!quiet_connex) message("connection using EXISTING ___________________________________ ")
      # if (!quiet_connex) print(.sfcon)

      ## SET DEFAULTS
      if (set_defaults) {
        list(wh=wh, dbname=dbname, schema=schema) %>% removeNullsAndBlanksFromList %>% {c(., list(connex=.sfcon, verbose=FALSE, warn=FALSE))} %>%
          do.call(.sf_use, .)
      }

      return(get(".sfcon", envir=envir))
    }
  }

  if (!assign) {
    warning ("Not assigning the sfGetCon is a mistake in the snowflake realm.  Every new connection looses the previous settings")
    return(do.call(odbcDriverConnect_wrapper, args_for_drv))
  }

  ## Create and assign simultaneously
  assign(".sfcon", do.call(odbcDriverConnect_wrapper, args_for_drv), envir=envir)
  .sfcon <- get(".sfcon", envir=envir)

  ## SET DEFAULTS
  if (set_defaults) {
    list(wh=wh, dbname=dbname, schema=schema) %>% removeNullsAndBlanksFromList %>% {c(., list(connex=.sfcon, verbose=FALSE, warn=FALSE))} %>%
      do.call(.sf_use, .)
  }

  if (!quiet_connex) message("----- NEW Snowflake connection established ___________________________________ ")
  if (!quiet_connex) print(.sfcon)

  return(.sfcon)
}


if (FALSE)
sfGetCon_old_as_of_20150721 <- function(uid=getOption("snowflake_uid"), pwd=getOption("snowflake_pwd"), drv=getOption("snowflake_driver")
  , wh=getSnowflakeWH(refresh=FALSE), dbname=getSnowflakeDB(refresh=FALSE), schema=getSnowflakeSchema(refresh=FALSE)
  , assign=TRUE, envir=.get_sfEnvir(), refresh=NULL, set_snowflake_inuse=TRUE, set_defaults=TRUE
  , quiet_connex=isTRUE(getOption("sfGetCon_quiet_connex"))) {

  ## Collect these one time, used often in do.call
  args_for_drv <- list(dsn=drv, uid=uid, pwd=pwd, warehouse=wh, database=dbname, schema=schema)

  if (is.null(drv))
    stop ("drv cannot be NULL.\n\nHINT: run   setSnowflakeOptions()")

  if (isTRUE(set_snowflake_inuse))
    options("snowflake_inuse" = TRUE)

  # connex_exists <- exists("sfcon", envir=envir) && RODBC:::odbcValidChannel(get("sfcon", envir=envir))
  # if (!isTRUE(refresh) && connex_exists) {
  if (!isTRUE(refresh) && exists(".sfcon", envir=envir, inherits=FALSE, mode="numeric")) {
    .sfcon <- get(".sfcon", envir=envir)
    # if (isConExpired(.sfcon)) {
    #   cat("expired - trying to reconnect ... ")
    #   assign(".sfcon", odbcReConnect(channel=.sfcon), envir=envir)
    #   .sfcon <- get(".sfcon", envir=envir)
    #   cat(ifelse(isConExpired(.sfcon), " FAILED :(", "Success!"), "\n")
    # }
    if (!isConExpired(.sfcon)) {
      if (!quiet_connex) message("connection using EXISTING ___________________________________ ")
      if (!quiet_connex) print(.sfcon)
      return(get(".sfcon", envir=envir))
    }
  }

  if (!assign) {
    warning ("Not assigning the sfGetCon is a mistake in the snowflake realm.  Every new connection looses the previous settings")
    return(do.call(odbcDriverConnect_wrapper, args_for_drv))
    # return(odbcConnect(drv, uid=uid, pwd=pwd))
  }

  ## Create and assign simultaneously
  assign(".sfcon", do.call(odbcDriverConnect_wrapper, args_for_drv), envir=envir)
  .sfcon <- get(".sfcon", envir=envir)

  ## SET DEFAULTS
  if (set_defaults) {
  # OLD:  getSnowflake(refresh=FALSE) %>% as.list %>% {c(., list(connex=.sfcon, verbose=FALSE, warn=FALSE))} %>%
  # NEW: 
    list(wh=wh, dbname=dbname, schema=schema) %>% {c(., list(connex=.sfcon, verbose=FALSE, warn=FALSE))} %>%
      do.call(.sf_use, .)
  }

  if (!quiet_connex) message("connection using NEW ___________________________________ ")
  if (!quiet_connex) print(.sfcon)

  return(.sfcon)
}

