

compareAndDelete(deleteFrom="~/!CLEAN/! RAW", compareTo="~/!CLEAN/", subDirsToExclude="! RAW")

compareAndDelete <- function(deleteFrom, compareTo, subDirsToExclude=NULL, trashBin="~/!DELETED") {
# subDirsToExclude should be a vector of strings.  

    ## ERROR CHECK
    if (! (is.character(deleteFrom) && is.character(compareTo) && (is.null(subDirsToExclude) || is.character(subDirsToExclude)) ) )
      stop("Not all arguments are Character")

    # CREATE TRASH BIN IF NECCESSARY 
    if (!file.exists(as.path(trashBin)))
      dir.create(as.path(trashBin))

    ## deleteCandidates are the files to possibly delete
    ## compAgainst is the list of all files, with path
    deleteCandidates <- list.files(as.path(deleteFrom), include.dirs=TRUE, recursive=TRUE)
    compAgainst <- list.files(as.path(compareTo), recursive=TRUE)

    ### EXCLUDE THE FOLLOWING SUBFOLDERS (if found anywhere)
    if (!is.null(subDirsToExclude)) {
      # first fix any beginning or trailing "/"
      subDirsExpr <- sub("/$", "",  sub("^/", "", subDirsToExclude))  # Remove starting and ending "/" if they exist
      subDirsExpr <-  sapply(subDirsExpr, function(x) paste0(c("^", "/"), x, "/")) # to avoid "/someFolder2/" matching when looking for "/Folder/"
      itemsToExclude <-   sapply(subDirsExpr, grep, compAgainst)
      compAgainst <- compAgainst[-unique(unlist(itemsToExclude))]  
    }

    # SPLICE OUT JUST THE FILENAMES
    compAgainst_Files <- sapply(strsplit(compAgainst, "/"), function(x) x[length(x)])
    deleteCandidates_Files <- sapply(strsplit(deleteCandidates, "/"), function(x) x[length(x)])

    # FIND ALL FILES THAT ARE ALREADY IN compAgainst.  THESE WILL BE MOVED TO TRASH
    n <- deleteCandidates_Files %in% compAgainst_Files

    # MOVE TO TRASH
    froms <- as.path(deleteFrom, deleteCandidates_Files[n])
    tos <- as.path(trashBin, deleteCandidates_Files[n])
    removed <- file.rename(from=froms, to=tos)

    ## ERROR CHECK THAT ALL WERE PROPERLY REMOVED
    if (!all(removed))
      warning("some files appear to be dups, but not removed")

    # ASSIGN NA TO ALL VALUES OF n THAT WERE NOT REMOVED BUT SHOULD HAVE BEEN  
    n[n] <- ifelse(removed, TRUE, NA)
    names(n) <- deleteCandidates
    return(n)
}
