SQL.folder.parent <- "~/git/orch/src/DeNormalizing/"
format_date6  <- "%y%m%d"


  ### -----  FIND LATEST FILES & FOLDERS -----  ###
      ## Grab the "AggregatedTables YYMMDD" folder with the latest date
      folders <- dir(SQL.folder.parent, pattern="^AggregatedTables")
      SQL.folder.last <- as.path(SQL.folder.parent, max(folders))

      ## Parse out the date
      lastDate <- stringr::str_extract(SQL.folder.last, pat="\\d{6}")

      ## The nextDate is today's date
      nextDate <- format(Sys.Date(), format=format_date6)


  ### -----  DUPLICATE, CLEAN, MOVE -----  ###
      if (nextDate == lastDate) {
        message("Current file is from today")
      } else {

        ####  -----  FOLDER  -----  #####
            ## DUPLICATE THE FOLDER
            SQL.folder.next <- gsub(lastDate, nextDate, SQL.folder.last)

            ## Create the new folder
            dir.create(SQL.folder.next, showWarnings=TRUE)

            ## Copy all the contents of the folder
            command.cp <- sprintf("cp %s/* %s", shellClean(SQL.folder.last), shellClean(SQL.folder.next))
            system(command.cp, TRUE)

        ####  -----  FILES  -----  #####
            ## Grab the files
            files <- dir(SQL.folder.next, full=TRUE)

            ## Grab their basenames
            filenames <- basename(files)

            ## only keep files that have the date in them
            keepThese <- grepl(lastDate, filenames)
            files     <- files[keepThese]
            filenames <- filenames[keepThese]

            ## Rename the files
            for (f.old in files) {
              f.new <- gsub(lastDate, nextDate, f.old)
              command.rn <- sprintf("mv %s %s", shellClean(f.old), shellClean(f.new))
              system (command.rn, TRUE)
            }

        ###  ARCHIVE THE OLD FOLDER
            command.mvfolder <- sprintf("mv %s %s/zArchived", shellClean(SQL.folder.last), shellClean(SQL.folder.parent))
            system(command.mvfolder, TRUE)

        message("New Folder Created: \n\t", SQL.folder.next)
      }


