
  # -------------------------------------------------------------------------------------------------------------------------  #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                            #
  #           File Name              :  googledocs.r                                                                           #
  #           Last Updated Funclist  :  15 Feb 2014,  1:13 AM (Saturday)                                                       #
  #                                                                                                                            #
  #           Author Name            :  Rick Saporta                                                                           #
  #           Author Email           :  RickSaporta@gmail.com                                                                  #
  #           Author URL             :  www.github.com/rsaporta                                                                #
  #                                                                                                                            #
  #           Packages Called        :  RGoogleDocs                                                                            #
  #           Packages Used via NS   :  NA                                                                                     #
  #                                                                                                                            #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                            #
  #   getGoogleDoc       ( googleDoc.file.name, worksheet.name="Weekly US Streaming Report", ignore.case=FALSE                 #
  #                        , verbose=TRUE, user, pw, simplify=TRUE, header.is.row.number=1L, skip.after.header.row=0L          #
  #                        , stringsAsFactor=FALSE )                                                                           #
  #                                                                                                                            #
  #                                                                                                                            #
  #                                                     <END FUNCS>                                                            #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  # -------------------------------------------------------------------------------------------------------------------------  #

getGoogleDoc <- function(googleDoc.file.name, worksheet.name="Weekly US Streaming Report", ignore.case=FALSE, verbose=TRUE, user, pw, simplify=TRUE, header.is.row.number=1L, skip.after.header.row=0L, stringsAsFactor=FALSE) {

  TODO:  IMPORT COLUMN FORMAT IS FUCKED UP
eg: 

                             V1      V2   V3          V4                    V5               V6
  1: Weekly US Streaming Report      NA   NA          NA                    NA               NA
  2:                         NA      NA   NA          NA                    NA               NA
  3:               Release Date Top 200 Heat       Genre                 Label              UPC
  4:                    41492.0      NA   NA Hip Hop/Rap              Rad Cult 8.88002023445E11
  5:                    41492.0      NA   NA        Rock       Relapse Records 7.81676721627E11
 ---
286:                    41149.0      NA   NA      Comedy     Courgette Records 8.87396302242E11
287:                    41149.0      NA   NA  Electronic Ghostly International 8.87396007475E11
288:                    41142.0      NA   NA Alternative    Frenchkiss Records  8.8739612932E11
289:                    41142.0      NA   NA  Electronic               Dim Mak 8.87396219908E11
290:                    41142.0      NA   NA Hip Hop/Rap    Gracie Productions 8.87396275997E11


  ## Ensure proper input for each value
  if (is.null(header.is.row.number))
    header.is.row.number <- 0L
  if (is.null(skip.after.header.row))
    skip.after.header.row <- 0L
  if (length(skip.after.header.row) != 1)
    stop("skip.after.header.row should be a single integer.\nTo drop a selection of rows, import the data first, then drop.")
  if (!is.numeric(header.is.row.number) || !is.numeric(skip.after.header.row))
    stop("header.is.row.number and skip.after.header.row should be numeric values. Set to 0L to ignore.")
  ## Calculate first row.  Note if both are zero, this will default to 1
  ind.from <- header.is.row.number + skip.after.header.row + 1


  require(RGoogleDocs)

  ## establish connection
  con  <- try(getGoogleDocsConnection(getGoogleAuth(user, pw, service = "wise")), silent=TRUE)
  if (isErr(con))
    stop("Could not connect to google docs. Double check your username/password. Error received was:\n", paste("\t",con))

  # Get list of docs
  docs <- getDocs(con)

  ## Confirm requested file exists in docs
  matched <- grep(googleDoc.file.name, names(docs), ignore.case=ignore.case)
  ## ... and that exactly one such file exists
  if(!length(matched))
    stop("File '", googleDoc.file.name, "' was not found.")
  if(length(matched) > 1)
    stop("Multiple matches found. Options are:\n\t", pasteQ(names(docs)[matched], wrap=NULL, collapse="\n\t"))

  ## Output
  if (verbose)
    cat("fetching '", names(docs)[[matched]], "' from Google Docs ....\n", sep="")

  ## Get that worksheet
  ws  <- getWorksheets(docs[[matched]], con)
  
  ## if worksheet.name is given, confirm that it is in names(ws)
  ## TODO:  allow for more than one worksheet name
  if (length(worksheet.name) && !all(worksheet.name %in% names(ws))) {
    warning(paste0("'", worksheet.name[!worksheet.name %in% names(ws)], "'", collapse=" and ")," not in names(ws).\n Using all worksheets.")
    worksheet.name <- NULL
  }

  ## if worksheet.name is NULL, grab all of them 
  if (is.null(worksheet.name))
    worksheet.name <- names(ws)

  ## Grab needed worksheets, converting to data.frame then data.table
  # ---------------------------------------------------------------- #

  ## Instead of simplifying after pulling the data (which requires an extra copy), use different code for each
    ret <- list()
    for (ws.nm in worksheet.name) {
      rawWS        <- sheetAsMatrix(ws[[ws.nm]], header=FALSE, as.data.frame=FALSE, trim=FALSE, stringsAsFactors=stringsAsFactor)
      rawWS2        <- sheetAsMatrix(ws[[ws.nm]], header=FALSE, as.data.frame=TRUE, trim=FALSE, stringsAsFactors=stringsAsFactor)
      ret[[ws.nm]] <- as.data.table(rawWS[seq(from=ind.from, to=nrow(rawWS)), ])
      ## Add header, if flagged
      if (header.is.row.number >= 1L)
        setnames(ret[[ws.nm]], as.character(rawWS[header.is.row.number, ]))
  }

  if (simplify && length(ret)==1)
    ret <- ret[[1]]

  return(ret)
}

# 
# 
# if (is.null(header.is.row.number))
#   header.is.row.number <- 0L
# if (is.null(skip.after.header.row))
#   skip.after.header.row <- 0L
# if (length(skip.after.header.row) != 1)
#   stop("skip.after.header.row should be a single integer.\nTo drop a selection of rows, import the data first, then drop.")
# if (!is.numeric(header.is.row.number) || !is.numeric(skip.after.header.row))
#   stop("header.is.row.number and skip.after.header.row should be numeric values. Set to 0L to ignore.")
# 
# ## Calculate first row.  Note if both are zero, this will default to 1
# ind.from <- header.is.row.number + skip.after.header.row + 1
# 
# rawWS <- sheetAsMatrix(ws[[ws.nm]], header=FALSE, as.data.frame=FALSE, trim=FALSE, stringsAsFactor=stringsAsFactor)
# 
# singleDT <- as.data.table(rawWS[seq(from=ind.from, to=nrow(rawWS)), ])
# 
# ## Add header, if flagged
# if (header.is.row.number >= 1L)
#   setnames(singleDT, as.character(rawWS[header.is.row.number, ]))
# 
# 
