# This breast cancer data was obtained from the University of Wisconsin
# Hospitals, Madison from Dr. William H. Wolberg.
# If 'download' is set to TRUE and the data is not already present locally, 
# it will be downloaded from:
# http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.names
# and stored in the sampleDataDir

"getBreastCancerData" <- function(download = TRUE, sampleDataDir = NULL, createDir = TRUE)
{
    sampleDataDir <- getSampleDataDir(sampleDataDir = sampleDataDir,
        createDir = createDir) 
    
    # Check to see if xdf files exist 
    dataPath <- file.path(sampleDataDir, "breastCancer.xdf")
    if (file.exists(dataPath))
    {
        breastCancer <- rxDataStep(dataPath)
        return( breastCancer )
    }
    if (!download)
    {
        stop(paste("Data file not available in: ", dataPath))
    }
    else
    {
        cat("Downloading and importing data to:", dataPath, "\n")
    }

    label.levels <- c(2, 4)
    label.name <- "Label"
    col.names <- c(
        "SampleCodeNumber", "ClumpThickness", "UniformityOfCellSize", "UniformityOfCellShape", 
        "MarginalAdhesion", "SingleEpithelialCellSize", "BareNuclei", "BlandChromatin", 
        "NormalNucleoli", "Mitoses", label.name)

    breast.cancer.desc <- "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data"
    
    breast.cancer <- try(read.csv(file.path(sampleDataDir, "breastCancer.csv"), col.names = col.names, header = FALSE, 
        check.names = FALSE, strip.white = TRUE, na.strings = "?", comment.char = "|", stringsAsFactors = FALSE))    
        
    breast.cancer <- try(read.csv(url(breast.cancer.desc), col.names = col.names, header = FALSE, 
        check.names = FALSE, strip.white = TRUE, na.strings = "?", comment.char = "|", stringsAsFactors = FALSE))
    stopifnot(!inherits(breast.cancer, "try-error"))

    breast.cancer[[label.name]] <- factor(breast.cancer[[label.name]], levels = label.levels, labels = c("benign","malignant") )
    
    breast.cancer <- breast.cancer[, c(label.name, col.names[2:(length(col.names) - 1)])] #reorder and get rid of "Sample code number"

     # Save to xdf file for future use
    rxDataStep(inData = breast.cancer, outFile = dataPath, overwrite = TRUE)  
    return(breast.cancer)   
}
