# Copyright (c) Microsoft Corporation.  All rights reserved.
#
# FUNCTIONS
#    Unit tests for rxFactors
#
############################################################################################
set.seed(100)
DF <- data.frame(Month = factor(sample(month.name, size = 20, replace = TRUE),
                            levels = rev(month.name)))

Q1 <- month.name[1:3]
Q2 <- month.name[4:6]
Q3 <- month.name[7:9]
Q4 <- month.name[10:12]

goodFactorInfo <- list(
            Quarter = list(newLevels = list(Q1 = Q1, Q2 = Q2, Q3 = Q3, Q4 = Q4), 
                           varName = "Month"))
                    
inXDF <- file.path(tempdir(), "in.xdf")
inDS <- RxXdfData(inXDF)
outXDF <- file.path(tempdir(), "out.xdf")
    
.setUp <- function()
{
    rxDataStep(DF, inXDF, overwrite = TRUE)
}

.tearDown <- function()
{
    inXDF <- file.path(tempdir(), "in.xdf")
    outXDF <- file.path(tempdir(), "out.xdf")
    if (file.exists(inXDF)) unlink(inXDF)
    if (file.exists(outXDF)) unlink(outXDF)
}

###
# Primary Argument Tests
###

"test.rxFactors.args.inData" <- function()
{
    # test for bad types
    checkException(rxFactors(inData = pi, outData = outXDF, factorInfo = goodFactorInfo, overwrite = TRUE), silent = TRUE)
    checkException(rxFactors(inData = NULL, outData = outXDF, factorInfo = goodFactorInfo, overwrite = TRUE), silent = TRUE)
    checkException(rxFactors(inData = c("a.xdf","b.xdf"), outData = outXDF, factorInfo = goodFactorInfo, overwrite = TRUE), silent = TRUE)
    
    # test for acceptable values
    newDF <- rxFactors(inData = DF, factorInfo = goodFactorInfo, overwrite = TRUE)
    z <- rxFactors(inData = inXDF, outFile = outXDF, factorInfo = goodFactorInfo, overwrite = TRUE)
    checkTrue(inherits(z, "RxXdfData"))
    fileDF <- rxDataStep(outXDF)
    checkEquals(newDF, fileDF)
    z <- rxFactors(inData = inDS, outFile = outXDF, factorInfo = goodFactorInfo, overwrite = TRUE)
    checkTrue(inherits(z, "RxXdfData"))
    fileDF <- rxDataStep(outXDF)
    checkEquals(newDF, fileDF)
}

"test.rxFactors.args.outFile" <- function()
{
    # test for bad types
    checkException(rxFactors(inData = inXDF, outData = pi, factorInfo = goodFactorInfo, overwrite = TRUE), silent = TRUE)
    checkException(rxFactors(inData = inXDF, outData = NULL, factorInfo = goodFactorInfo, overwrite = TRUE), silent = TRUE)
    checkException(rxFactors(inData = inXDF, outData = c("a.xdf","b.xdf"), factorInfo = goodFactorInfo, overwrite = TRUE), silent = TRUE)
    
    # test for acceptable values
    z <- rxFactors(inData = inXDF, outFile = outXDF, factorInfo = goodFactorInfo, overwrite = TRUE)
    checkTrue(inherits(z, "RxXdfData"))
    outXDF2 <- file.path(tempdir(), "out2.xdf")
    if (file.exists(outXDF2)) unlink(outXDF2)
    z <- rxFactors(inData = inXDF, outFile = outXDF2, factorInfo = goodFactorInfo, overwrite = TRUE)
    checkTrue(inherits(z, "RxXdfData"))
    checkEquals(rxDataStep(outXDF2), rxDataStep(outXDF))
    if (file.exists(outXDF2)) unlink(outXDF2)
}

"test.rxFactors.args.overwrite" <- function()
{
    # test for bad types
    checkException(rxFactors(inData = inXDF, outData = outXDF, factorInfo = goodFactorInfo, overwrite = pi), silent = TRUE)
    checkException(rxFactors(inData = inXDF, outData = outXDF, factorInfo = goodFactorInfo, overwrite = NULL), silent = TRUE)
    checkException(rxFactors(inData = inXDF, outData = outXDF, factorInfo = goodFactorInfo, overwrite = c(TRUE, FALSE)), silent = TRUE)
    
    # test for acceptable values
    inXDF2 <- file.path(tempdir(), "inTemp.xdf")
    rxDataStep(DF, inXDF2, overwrite = TRUE)    
    checkException(rxFactors(inData = inXDF2, outFile = inXDF2, factorInfo = goodFactorInfo, overwrite = FALSE), silent = TRUE)
    z <- rxFactors(inData = inXDF2, outFile = inXDF2, factorInfo = goodFactorInfo, overwrite = TRUE)
    checkTrue(inherits(z, "RxXdfData"))
    if (file.exists(inXDF2)) unlink(inXDF2)  
}

"test.rxFactors.args.blocksPerRead" <- function()
{
	test100r5b <- file.path(rxGetOption("unitTestDataDir"), "test100r5b")
	#Var 9: xfac2
    #10 factor levels: f c d e i g b j a h
    factorInfo <- list("xfac2" = list(sortLevels = TRUE),
                       "ylogical" = list(sortLevels = TRUE))
    
    varInfo <- rxGetVarInfo(test100r5b)
    
    blocksDefaultXdf <- file.path(tempdir(), "blocksDefault.xdf")
    blocks1Xdf <- file.path(tempdir(), "blocks1.xdf")
    blocks5Xdf <- file.path(tempdir(), "blocks5.xdf")
       
	z <- rxFactors(inData = test100r5b, outFile = blocksDefaultXdf, factorInfo = factorInfo, overwrite = TRUE, blocksPerRead = -1L)
    checkTrue(inherits(z, "RxXdfData"))
    z <- rxFactors(inData = test100r5b, outFile = blocks1Xdf, factorInfo = factorInfo, overwrite = TRUE, blocksPerRead = 1L)
    checkTrue(inherits(z, "RxXdfData"))   
	z <- rxFactors(inData = test100r5b, outFile = blocks5Xdf, factorInfo = factorInfo, overwrite = TRUE, blocksPerRead = 5L)
    checkTrue(inherits(z, "RxXdfData"))	
    
    blocksDefaultDF <- rxDataStep(blocksDefaultXdf)
    blocks1DF <- rxDataStep(blocks1Xdf)
    blocks5DF <- rxDataStep(blocks5Xdf)
    
    checkTrue(all(names(blocksDefaultDF) %in% names(varInfo)))
    checkEquals(levels(blocksDefaultDF[["xfac2"]]),  sort(varInfo[["xfac2"]][["levels"]]))
    checkEquals(levels(blocksDefaultDF[["ylogical"]]),  sort(varInfo[["ylogical"]][["levels"]]))
    checkEquals(blocksDefaultDF, blocks1DF)
    checkEquals(blocks1DF, blocks5DF)
    
    if (file.exists(blocksDefaultXdf)) unlink(blocksDefaultXdf)
    if (file.exists(blocks1Xdf)) unlink(blocks1Xdf)
    if (file.exists(blocks5Xdf)) unlink(blocks5Xdf)
}

"test.rxFactors.args.reportProgress" <- function()
{
	#reportProgress: logical, character string or integer: 
	#  0: no progress is reported. 
	#  1: the number of processed rows is printed and updated. 
	#  2: rows processed and timings are reported. 
	#  3: rows processed and all timings are reported. 

	variations <- list(0,1,2,3)	
	results <- printOutput <- vector("list", length=length(variations))
	
	for (i in seq_along(variations))
	{
		printOutput[[i]] <- capture.output(results[[i]] <- 
            rxFactors(inData = inXDF, outFile = outXDF, factorInfo = goodFactorInfo, overwrite = TRUE, 
                reportProgress = variations[[i]], verbose = 0L))
	}

	# check that all values are the same
	names(printOutput) <- as.character(variations)
	noResponseExpected <- c("0")
	equalLengthExpected <- c("2")
	equalLengthExpected1 <- c("1")
	
	checkTrue(length(unlist(printOutput[noResponseExpected])) == 0L)
	
	# all these outputs should be the same
	checkTrue(length(printOutput[equalLengthExpected]) > 0L)
	
	# details gives us the goods
	checkTrue(length(grep("ReadNum=1, CurrentBlockNum=2, CurrentNumRows=20, TotalRowsProcessed=20, ReadTime", 
		printOutput[["3"]][1])) > 0L)
	
	# time
	checkTrue(length(grep("^Rows Read:", printOutput[["2"]][1L])) > 0L)
}

"test.rxFactors.args.verbose" <- function()
{
    o1 <- capture.output(test1 <- rxFactors(inData = inXDF, outFile = outXDF, factorInfo = goodFactorInfo, 
                                                  overwrite = TRUE, reportProgress = 0))
    o2 <- capture.output(test2 <- rxFactors(inData = inXDF, outFile = outXDF, factorInfo = goodFactorInfo, 
                                                  overwrite = TRUE, verbose = 0, reportProgress = 0))
    o3 <- capture.output(test3 <- rxFactors(inData = inXDF, outFile = outXDF, factorInfo = goodFactorInfo, 
                                                  overwrite = TRUE, verbose = 1, reportProgress = 0))
    checkEquals(length(o1), 0)
    checkEquals(length(o2), 0)
    checkTrue(length(o3) > 1)
}

###
# factorInfo Argument Tests
###
"test.rxFactors.args.factorInfo.list" <- function()
{
    testXdf1 <- tempfile(pattern = ".rxFactorsTest1", fileext = ".xdf")
    testXdf2 <- tempfile(pattern = ".rxFactorsTest2", fileext = ".xdf")
    inTextFile <- file.path(rxGetOption("unitTestDataDir"), "test100r.txt")
    rxImport(inData = inTextFile, outFile = testXdf1, stringsAsFactors = FALSE, 
        rowsPerRead = 30, overwrite = TRUE)
    
    facinfoList <- list(newXfac1 = list(varName = "xfac1"))
                    
	if (file.exists(testXdf2)) unlink(testXdf2)
	rxFactors(inData = testXdf1, factorInfo = facinfoList, 
		outFile = testXdf2, overwrite = TRUE ) 
    
    varInfo <- rxGetVarInfo(testXdf2)
    checkEquals(varInfo$newXfac1$varType, "factor")               
                        
    file.remove(testXdf1)
    file.remove(testXdf2)    
}

"test.rxFactors.args.factorInfo.newLevels" <- function()
{
	# In the case that newLevels is an un-named character vector
    # and the length of newLevels is less than or equal to that of the existing levels, 
    # check that we throw an error if not all of the 'newLevels' values are in the
    # set of existing levels. 
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["newLevels"]] <- c("December", "January", "Feb", "Cow")
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)

	# In the case that newLevels is an un-named character vector
    # and the length of newLevels is greater than that of the existing levels, 
    # check that we throw an error if not all existing levels are in the 'newLevels'. 
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["newLevels"]] <- c(month.name[-(1:3)], letters)
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)

	# check bad type for newLevels
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["newLevels"]] <- 1:4
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)

	# check bad type for newLevels
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["newLevels"]] <- character(0)
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)

	# check for blank entry in newLevels
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["newLevels"]] <- c(month.name[-1L], "")
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)
}

"test.rxFactors.args.factorInfo.indexMap" <- function()
{
    # rearrange levels to be in alphabetical order, the hard way
    indexMap <- match(levels(DF[["Month"]]), month.name)
    newDF <- rxFactors(DF, factorInfo = list(Month = list(newLevels = month.name, indexMap = indexMap, 
		varName = "Month")))
    checkEquals(levels(newDF[["Month"]]), month.name)
    
    # check that newLevels must also be specified if indexMap is specified
    checkException(rxFactors(DF, factorInfo = list(Month = list(indexMap = indexMap))), silent = TRUE)
    
	# check number of indexMap entries does not match existing number of levels
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["indexMap"]] <- 1:13
	badFactorInfo[["Quarter"]][["newLevels"]] <- month.name
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)

	# check bad type for indexMap 
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["indexMap"]] <- letters[1:12]
	badFactorInfo[["Quarter"]][["newLevels"]] <- month.name
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)

    # check bad type for indexMap 
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["indexMap"]] <- integer(0)
	badFactorInfo[["Quarter"]][["newLevels"]] <- month.name
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)
}	

"test.rxFactors.args.factorInfo.combo.xdf" <- function()
{
    # RA-6711
    x1 <- rep(c("a","b"), each = 5)
    x2 <- rep(c(-1,2), times = 5)
    myData <- data.frame(x1, x2, stringsAsFactors = FALSE)
    testXdf1 <- tempfile(pattern = "rxFactors1", fileext = ".xdf")
    testXdf2 <- tempfile(pattern = "rxFactors2", fileext = ".xdf")
    rxDataStep(inData = myData, outFile = testXdf1, overwrite = TRUE)
    facinfo <- list(
        x1fac = list(varName = "x1"),
        x2new = list(levels = c(-1,2), newLevels = c("I", "II"), varName = "x2"))	

    if (file.exists(testXdf2)) file.remove(testXdf2)
    myNewData <- rxFactors(inData = testXdf1, factorInfo = facinfo,
        outFile = testXdf2)
    varInfo <- rxGetVarInfo(myNewData)
    
    checkEquals(varInfo$x1fac$levels, c("a", "b"))
    checkEquals(varInfo$x2new$levels, c("I", "II"))
    
    file.remove(testXdf1)
    file.remove(testXdf2)

}
"test.rxFactors.args.data.dataTypes" <- function()
{
	testData <- data.frame(
		VarDbl = c(1.234090928430923, 2.1231312312, 3.12312312312,  4.5, 5.0),
		VarInt = as.integer(c(1,2,3,2,1)),
		VarChar = c("One", "Two", "Three", "Two", "One"), 
		VarChar2 = c("One", "Two", "Three", "Two", "One"), 
		stringsAsFactors = FALSE
		)
	
	myData <- rxFactors(testData ,factorInfo = list(
		VarDblFac = list(varName = "VarDbl"), 
		VarIntFac = list(varName = "VarInt"), 
		VarCharFac = list(varName = "VarChar"),
		VarCharFac2 = list(varName = "VarChar2", sortLevels = TRUE, levels = c("One",  "Two", "Three")))
		)
	varInfo <- rxGetVarInfo(myData)
	checkEquals(varInfo$VarDblFac$varType, "factor")
	checkEquals(varInfo$VarDblFac$levels, c("1.234091","2.123131", "3.123123", "4.5","5")) 
	checkEquals(varInfo$VarIntFac$varType, "factor")
	checkEquals(varInfo$VarIntFac$levels, c("1", "2", "3")) 
	checkEquals(varInfo$VarCharFac$varType, "factor")
	checkEquals(varInfo$VarCharFac$levels, c("One",  "Two", "Three")) 
	checkEquals(varInfo$VarCharFac2$varType, "factor")
	checkEquals(varInfo$VarCharFac2$levels, c("One", "Three", "Two" )) 
}

    
"test.rxFactors.args.factorInfo.sortLevels" <- function()
{
	# fix for RA-4214
	# check bad type for sortLevels 
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["sortLevels"]] <- pi
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)
	badFactorInfo[["Quarter"]][["sortLevels"]] <- logical(0)
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)
	badFactorInfo[["Quarter"]][["sortLevels"]] <- c(FALSE, TRUE)
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)
    
    # create factor variable with levels not in alphabetical order
    DF <- data.frame(alphabet = factor(rep(letters, each = 3), levels = rev(letters)))
    newLevels <- c(B = "b", A = "a", C = "c")
    originalLevels <- levels(DF[["alphabet"]])

    # Recode a subset of levels, putting other into a category "a", and sort the resulting levels
    factorInfo <- list(alphabet = list(newLevels = newLevels, otherLevel = "a", sortLevels = TRUE))
    newDF <- rxFactors(DF, factorInfo)
    tempLevels <- levels(newDF[["alphabet"]])
    cat("rxFactor tempLevels", tempLevels, "\n")
    checkEquals(tempLevels, c( "A", "B", "C", "a"))

    # Recode a subset of levels, putting other into a category "a", and leave order as specified
    factorInfo <- list(alphabet = list(newLevels = newLevels, otherLevel = "a", sortLevels = FALSE))
    newDF <- rxFactors(DF, factorInfo)
    checkEquals(levels(newDF[["alphabet"]]), c("B", "A", "C", "a"))

    #####
    # Test default setting of sortLevels with level exclusion
    
    unsortedLevels <- c("B", "A", "C", "a")
    sortedLevels <- c("A", "B", "C", "a")

    # global TRUE
    factorInfo <- list(alphabet = list(newLevels = newLevels, otherLevel = "a"))
    newDF <- rxFactors(DF, factorInfo, sortLevels = TRUE)
    checkEquals(levels(newDF[["alphabet"]]), sortedLevels)

    # global FALSE
    factorInfo <- list(alphabet = list(newLevels = newLevels, otherLevel = "a"))
    newDF <- rxFactors(DF, factorInfo, sortLevels = FALSE)
    checkEquals(levels(newDF[["alphabet"]]), unsortedLevels)
    
    # global FALSE, overwritten by local TRUE
    factorInfo <- list(alphabet = list(newLevels = newLevels, otherLevel = "a", sortLevels = TRUE))
    newDF <- rxFactors(DF, factorInfo, sortLevels = FALSE)
    checkEquals(levels(newDF[["alphabet"]]), sortedLevels)
   
    # global TRUE, overwritten by local FALSE
    factorInfo <- list(alphabet = list(newLevels = newLevels, otherLevel = "a", sortLevels = FALSE))
    newDF <- rxFactors(DF, factorInfo, sortLevels = TRUE)
    checkEquals(levels(newDF[["alphabet"]]), unsortedLevels)

    #####
    # Test default setting of sortLevels without level exclusion
    
    unsortedLevels <- rev(c(LETTERS[1:3], letters[-(1:3)]))
    sortedLevels <- sort(unsortedLevels)
    
    # global TRUE
    factorInfo <- list(alphabet = list(newLevels = newLevels))
    newDF <- rxFactors(DF, factorInfo, sortLevels = TRUE)
    checkEquals(levels(newDF[["alphabet"]]), sortedLevels)

    # global FALSE
    factorInfo <- list(alphabet = list(newLevels = newLevels))
    newDF <- rxFactors(DF, factorInfo, sortLevels = FALSE)
    checkEquals(levels(newDF[["alphabet"]]), unsortedLevels)
    
    # global FALSE, overwritten by local TRUE
    factorInfo <- list(alphabet = list(newLevels = newLevels, sortLevels = TRUE))
    newDF <- rxFactors(DF, factorInfo, sortLevels = FALSE)
    checkEquals(levels(newDF[["alphabet"]]), sortedLevels)
   
    # global TRUE, overwritten by local FALSE
    factorInfo <- list(alphabet = list(newLevels = newLevels, sortLevels = FALSE))
    newDF <- rxFactors(DF, factorInfo, sortLevels = TRUE)
    checkEquals(levels(newDF[["alphabet"]]), unsortedLevels)
}
"test.rxFactors.args.factorInfo.sortLevels.character" <- function()
{
	# Sorting factor levels from character data takes 2 passes
	# through rxFactors.  Need to test this code path
	testXdf <- file.path(rxGetOption("unitTestDataDir"), "richTest100r5b.xdf")
	outXdf <- tempfile(pattern = ".rxFactorChar", fileext = ".xdf")
	rxFactors(testXdf, factorInfo = "z.char1", sortLevels = TRUE, outFile = outXdf, overwrite = TRUE)
	varInfo <- rxGetVarInfo(outXdf)
	checkEquals(varInfo$z.char1$varType, "factor")
	checkEquals(varInfo$z.char1$levels, c("Alaska","North Carolina","Washington")) 
	file.remove(outXdf)
}

"test.rxFactors.args.factorInfo.sortLevels.only" <- function()
{
	# Checks for cases where the only request is to sort factor levels
	claimsXdf <- file.path(rxGetOption("sampleDataDir"), "claims.xdf")
	claimsNewXdf <- tempfile(pattern = ".rxFactorTest", fileext = ".xdf") 
	claimsCopyXdf <- tempfile(pattern = ".rxClaimsCopy", fileext = ".xdf") 
	if (file.exists(claimsNewXdf)) file.remove(claimsNewXdf) 
	claimsDataFrame <- rxDataStep(claimsXdf) 
	file.copy(from = claimsXdf, to = claimsCopyXdf, copy.mode = FALSE)
    on.exit(unlink(claimsCopyXdf), add = TRUE)

	####################################################################################
	# The factor age is already in order; make sure warnings and output appropriate
	# Case 1: data frame in and out should be the same
	
	output1 <- rxFactors(inData = claimsDataFrame, factorInfo= list(age=list(sortLevels=TRUE)))
	checkEquals(claimsDataFrame, output1)
	
	output1a <- rxFactors(inData = claimsDataFrame, sortLevels = TRUE, factorInfo= c("age"))
	checkEquals(claimsDataFrame, output1a) 
		
	# Case 2: xdf in, data frame out
	output2 <- rxFactors(inData = claimsXdf, factorInfo= list(age=list(sortLevels=TRUE)))
	checkEquals(claimsDataFrame, output2)
	
	# Case 3: xdf in, same xdf out
	output3 <- rxFactors(inData = claimsCopyXdf, outFile = claimsCopyXdf, 
		factorInfo= list(age=list(sortLevels=TRUE)), overwrite = TRUE)
	checkEquals(normalizePath(output3@file), normalizePath(claimsCopyXdf))
	
	# Case 4: xdf in, different xdf out
	output4 <- rxFactors(inData = claimsXdf, outFile = claimsNewXdf, 
		factorInfo= list(age=list(sortLevels=TRUE)), overwrite = TRUE)
	checkEquals(normalizePath(output4@file), normalizePath(claimsNewXdf))
	
	# Case 5: data frame in, xdf out
	if ( file.exists(claimsNewXdf)) file.remove(claimsNewXdf)
	output5 <- rxFactors(inData = claimsDataFrame, outFile = claimsNewXdf,
 		factorInfo= list(age=list(sortLevels=TRUE)))
	checkEquals(normalizePath(output5@file), normalizePath(claimsNewXdf))

	
	# Clean-up
	rm(output1)
	rm(output2)
	rm(output3)
	rm(output4)
	
	#############################################################################
	# Look at case where levels actually need sorting
	############################################################################

	testXdf <- file.path(rxGetOption("unitTestDataDir"), "test100r5b.xdf")
	testNewXdf <- tempfile(pattern = ".rxFactorTest2", fileext = ".xdf") 
	testCopyXdf <- tempfile(pattern = ".rxFactorTest2", fileext = ".xdf") 
	file.copy(from = testXdf, to = testCopyXdf, copy.mode = FALSE)
	testDataFrame <- rxDataStep(testXdf) 
	
	# Case 1: data frame in and out; levels out should be same as sorted levels in
	output1 <- rxFactors(inData = testDataFrame, factorInfo= list(xfac1=list(sortLevels=TRUE)))
	checkEquals(levels(output1$xfac1), sort(levels(testDataFrame$xfac1)))
	
	# Case 2: xdf in, data frame out
	output2 <- rxFactors(inData = testXdf, factorInfo= list(xfac1=list(sortLevels=TRUE)))
	checkEquals(levels(output2$xfac1), sort(levels(testDataFrame$xfac1)))
	
	# Case 3: xdf in, same xdf out
	output3 <- rxFactors(inData = testCopyXdf, outFile = testCopyXdf, 
		factorInfo= list(xfac1=list(sortLevels=TRUE)), overwrite = TRUE)
	varInfo3 <- rxGetVarInfo( output3 )	
	checkEquals(varInfo3$xfac1$levels, sort(levels(testDataFrame$xfac1)))
	
	# Case 4: xdf in, different xdf out
	output4 <- rxFactors(inData = testXdf, outFile = testNewXdf, 
		factorInfo= list(xfac1=list(sortLevels=TRUE)))
	varInfo4 <- rxGetVarInfo( output4 )
	checkEquals(varInfo4$xfac1$levels, sort(levels(testDataFrame$xfac1)))
	
	file.remove(testCopyXdf)
	file.remove(testNewXdf)
	
	############################################################################
	# Look at the case of sorting vector of factor variable names
	###########################################################################
	
	testXdf <- file.path(rxGetOption("unitTestDataDir"), "test100r5b.xdf")
	testNewXdf <- tempfile(pattern = ".rxFactorTest2", fileext = ".xdf") 
	testCopyXdf <- tempfile(pattern = ".rxFactorTest2", fileext = ".xdf") 
	file.copy(from = testXdf, to = testCopyXdf, copy.mode = FALSE)
	testDataFrame <- rxDataStep(testXdf) 
	
	# Case 1: data frame in and out; levels out should be same as sorted levels in
	output1 <- rxFactors(inData = testDataFrame, sortLevels = TRUE,
		factorInfo= c("xfac1", "xfac2"))
	checkEquals(levels(output1$xfac1), sort(levels(testDataFrame$xfac1)))
	checkEquals(levels(output1$xfac2), sort(levels(testDataFrame$xfac2)))
	
	# Case 2: xdf in, data frame out
	output2 <- rxFactors(inData = testXdf, sortLevels = TRUE,
		factorInfo= c("xfac1", "xfac2"))
	checkEquals(levels(output2$xfac1), sort(levels(testDataFrame$xfac1)))
	checkEquals(levels(output2$xfac2), sort(levels(testDataFrame$xfac2)))
	
	# Case 3: xdf in, same xdf out
	output3 <- rxFactors(inData = testCopyXdf, outFile = testCopyXdf, 
		sortLevels = TRUE,
		factorInfo= c("xfac1", "xfac2"), overwrite = TRUE)
	varInfo3 <- rxGetVarInfo( output3 )	
	checkEquals(varInfo3$xfac1$levels, sort(levels(testDataFrame$xfac1)))
	checkEquals(varInfo3$xfac2$levels, sort(levels(testDataFrame$xfac2)))
	
	# Case 4: xdf in, different xdf out
	output4 <- rxFactors(inData = testXdf, outFile = testNewXdf, 
		sortLevels = TRUE,
		factorInfo= c("xfac1", "xfac2"))
	varInfo4 <- rxGetVarInfo( output4 )
	checkEquals(varInfo4$xfac1$levels, sort(levels(testDataFrame$xfac1)))
	checkEquals(varInfo4$xfac2$levels, sort(levels(testDataFrame$xfac2)))
	
	file.remove(testCopyXdf)
	file.remove(testNewXdf)
    file.remove(claimsNewXdf)
    file.remove(claimsCopyXdf)
	rm(output1)
	rm(output2)
	rm(output3)
	rm(output4)
	
	############################################################################
	# Look at the case of sorting all factors by default with no factorInfo
	###########################################################################
	
	testXdf <- file.path(rxGetOption("unitTestDataDir"), "test100r5b.xdf")
	testNewXdf <- tempfile(pattern = ".rxFactorTest2", fileext = ".xdf") 
	testCopyXdf <- tempfile(pattern = ".rxFactorTest2", fileext = ".xdf") 
	file.copy(from = testXdf, to = testCopyXdf, copy.mode = FALSE)
	testDataFrame <- rxDataStep(testXdf) 
	
	# Case 1: data frame in and out; levels out should be same as sorted levels in
	output1 <- rxFactors(inData = testDataFrame, sortLevels = TRUE )
	checkEquals(levels(output1$xfac1), sort(levels(testDataFrame$xfac1)))
	checkEquals(levels(output1$xfac2), sort(levels(testDataFrame$xfac2)))
	checkEquals(levels(output1$ylogical), sort(levels(testDataFrame$ylogical)))
	
	# Case 2: xdf in, data frame out
	output2 <- rxFactors(inData = testXdf, sortLevels = TRUE)
	checkEquals(levels(output2$xfac1), sort(levels(testDataFrame$xfac1)))
	checkEquals(levels(output2$xfac2), sort(levels(testDataFrame$xfac2)))
	checkEquals(levels(output2$ylogical), sort(levels(testDataFrame$ylogical)))
	
	# Case 3: xdf in, same xdf out
	output3 <- rxFactors(inData = testCopyXdf, outFile = testCopyXdf, 
		sortLevels = TRUE, overwrite = TRUE)
	varInfo3 <- rxGetVarInfo( output3 )	
	checkEquals(varInfo3$xfac1$levels, sort(levels(testDataFrame$xfac1)))
	checkEquals(varInfo3$xfac2$levels, sort(levels(testDataFrame$xfac2)))
	checkEquals(varInfo3$ylogical$levels, sort(levels(testDataFrame$ylogical)))
	
	# Case 4: xdf in, different xdf out
	output4 <- rxFactors(inData = testXdf, outFile = testNewXdf, 
		sortLevels = TRUE )
	varInfo4 <- rxGetVarInfo( output4 )
	checkEquals(varInfo4$xfac1$levels, sort(levels(testDataFrame$xfac1)))
	checkEquals(varInfo4$xfac2$levels, sort(levels(testDataFrame$xfac2)))
	checkEquals(varInfo4$ylogical$levels, sort(levels(testDataFrame$ylogical)))
	
	file.remove(testCopyXdf)
	file.remove(testNewXdf)
	
}


"test.rxFactors.args.factorInfo.varName" <- function()
{
	# check bad type for varName 
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["varName"]] <- pi
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)
    
    # empty string check
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["varName"]] <- ""
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)

    # multiple string check
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["varName"]] <- letters
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)
    
    # ensure that 'varName' names do not intersect with any existing names in 'inData'
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["varName"]] <- "boink"
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)
    
    # check for rename
	newDF <- rxFactors(DF, factorInfo = goodFactorInfo)
    checkTrue(goodFactorInfo[["Quarter"]][["varName"]] %in% names(newDF))
}

"test.rxFactors.args.factorInfo.description" <- function()
{
	# check bad type for varName 
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["description"]] <- pi
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)
    
    # empty string check
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["description"]] <- NA
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)

    # multiple string check
    badFactorInfo <- goodFactorInfo
	badFactorInfo[["Quarter"]][["description"]] <- letters
	checkException(rxFactors(DF, factorInfo = badFactorInfo), silent = TRUE)    
}

###
# Story Tests
###

"test.rxFactors.alphabetize.levels" <- function()
{
    # Reorder 'tension' levels alphabetically
    recodedDF <- rxFactors(inData = warpbreaks, 
                           factorInfo = list(tension = list(sortLevels = TRUE)))

    # write data frame to .xdf file and perform similar recoding
    # but write the recoded factor to a new variable. Compare the
    # original with the recoded factor.
    inXDF <- file.path(tempdir(), "warpbreaks.xdf")
    outXDF <- file.path(tempdir(), "warpbreaksRecoded.xdf")
    rxDataStep(warpbreaks, outFile = inXDF, overwrite = TRUE)
    rxFactors(inData = inXDF, outFile = outXDF, overwrite = TRUE,
              factorInfo = list(recodedTension= list(sortLevels = TRUE, 
                                                varName = "tension")))
    recodedXDF <- rxDataStep(outXDF)
    checkEquals(levels(recodedDF[["tension"]]), sort(levels(warpbreaks[["tension"]])))
    checkEquals(levels(recodedXDF[["recodedTension"]]), sort(levels(warpbreaks[["tension"]])))

    # clean up
    if (file.exists(inXDF)) unlink(inXDF)
    if (file.exists(outXDF)) unlink(outXDF)   
}

"test.rxFactors.levels.indexes" <- function()
{
    # Recoding levels and indexes, saving recoding to a new factor variable

    # Create an .xdf file with a factor variable named 'sex' with levels 'M and 'F'
    # with corresponding indexes 1 and 2, respectively.
    set.seed(100)
    sex <- factor(sample(c("M","F"), size = 10, replace = TRUE), levels = c("M", "F"))
    DF <- data.frame(sex = sex, score = rnorm(10))
    XDF <- file.path(tempdir(), "sex.xdf")
    XDF2 <- file.path(tempdir(), "sex2.xdf")
    rxDataStep(DF, outFile = XDF, overwrite = TRUE)

    # Assume that we change our minds and now wish to 
    # rename the levels to "Female" and "Male" with indexes 2 and 1, 
    # respectively. Let us do the recoding and store the result into a new
    # variable named "Gender" keeping the old variable in place.
    rxFactors(inData = XDF, outFile = XDF2, overwrite = TRUE,
                    factorInfo = list(Gender = list(newLevels = c("Female" = "F", "Male" = "M"), 
                                                    varName = "sex")))
    newDF <- rxDataStep(XDF2)
    checkEquals(levels(newDF[["Gender"]]), c("Female", "Male"))
    checkEquals(newDF[["sex"]], DF[["sex"]])
    
    # clean up
    if (file.exists(XDF)) unlink(XDF)
    if (file.exists(XDF2)) unlink(XDF2)
}

"test.rxFactors.subset.recombination" <- function()
{
    # Combining subsets of factor levels into single levels

    # Create a data set that contains a factor variable 'Month'
    # Note that the levels are not in alphabetical order.
    set.seed(100)
    DF <- data.frame(Month = factor(sample(month.name, size = 20, replace = TRUE),
                                    levels = rev(month.name)))

    # Recode the months into quarters and store result into new variable named "Quarter"
    recodedDF <- rxFactors(inData = DF, 
        factorInfo = list(Quarter = list(newLevels = list(Q1 = month.name[1:3], 
                                                          Q2 = month.name[4:6],
                                                          Q3 = month.name[7:9], 
                                                          Q4 = month.name[10:12]),
                                         varName = "Month")))
                                                 
    checkEquals(levels(recodedDF[["Quarter"]]), paste("Q", 1:4, sep = ""))
    
    key <- month.name
    names(key) <- paste("Q", rep(1:4, each = 3), sep = "")
    monthValues <- as.character(DF[["Month"]])
    monthVauesInQuarters <- names(key[match(monthValues, key)])
    checkEquals(as.character(recodedDF[["Quarter"]]), monthVauesInQuarters)
}

"test.rxFactors.compare.dataframe.xdf" <- function()
{
    # define inputs
    DF <- data.frame(sex = c('Male', 'Male', 'Female', 'Male'), 
	                 age = factor(c(20, 20, 12, 15)), 
	                 sport = c('tennis', 'golf', 'football', 'basketball'))

    factorInfo <- list(
        sex = list(newLevels = c(male = "Male", female = "Female")),
	    age = list(newLevels = list(Young = c("12","15"), Old = "20")),
	    TeamSport = list(newLevels = list(individual = c('tennis', 'golf'), team = c('football', 'basketball')),
                     varName = "sport")
        )
            
    newDF <- rxFactors(DF, factorInfo = factorInfo, reportProgress = 0L)

    # perform recoding on data frame and equivalent .xdf file
    inXDF <- file.path(tempdir(), "Sports.xdf")
    outXDF <- file.path(tempdir(), "newSports.xdf")
    if (file.exists(inXDF)) unlink(inXDF)
    if (file.exists(outXDF)) unlink(outXDF)
    rxDataStep(DF, inXDF)
    rxFactors(inXDF, outFile = outXDF, factorInfo = factorInfo, overwrite = TRUE)
    newDF2 <- rxDataStep(outXDF)
    
    # test the outputs
    checkEquals(newDF[names(newDF2)], newDF2)
    checkEquals(levels(newDF[["sex"]]), c("male", "female"))
    checkEquals(levels(newDF[["age"]]), c("Young", "Old"))
    checkEquals(levels(newDF[["TeamSport"]]), c("individual", "team"))
    checkEquals(names(newDF), c("sex", "age", "sport", "TeamSport"))    
    
    # clean up
    if (file.exists(inXDF)) unlink(inXDF)
    if (file.exists(outXDF)) unlink(outXDF)
}

"test.rxFactors.compare.char.fixed" <- function()
{
    # define inputs
    DF <- data.frame(sex = c('Male', 'Male', 'Female', 'Male'), 
	                 age = factor(c(20, 20, 12, 15)), 
	                 sport = c('tennis', 'golf', 'football', 'basketball'), 
					 stringsAsFactors = FALSE)
		
    inXdfChar <- file.path(tempdir(), "sportsChar.xdf")
    inXdfFixed <- file.path(tempdir(), "sportsFixed.xdf")
	on.exit(unlink(inXdfChar), add = TRUE)
	on.exit(unlink(inXdfFixed), add = TRUE)
	rxDataStep(DF, outFile = inXdfChar, rowsPerRead = 3)
	
	
	attr(DF$sex, ".rxColWidth") <- as.integer(6)
	attr(DF$sport, ".rxColWidth") <- as.integer(10)
	rxDataStep(DF, outFile = inXdfFixed, rowsPerRead = 3)
	
    factorInfo <- c("sex", "sport")        
    newDF1 <- rxFactors(inXdfChar,  factorInfo = factorInfo, reportProgress = 0L)
    newDF2 <- rxFactors(inXdfFixed, factorInfo = factorInfo, reportProgress = 0L)
	
	checkEquals(newDF1, newDF2)
        
    # clean up
    if (file.exists(inXdfChar)) unlink(inXdfChar)
    if (file.exists(inXdfFixed)) unlink(inXdfFixed)
}
###
# Argument combination tests
###

"test.rxFactors.args.inData.outFile" <- function()
{
    DF <- data.frame(sex = c('Male', 'Male', 'Female', 'Male'), 
	                 age = c(20, 20, 12, 15), 
	                 sport = c('tennis', 'golf', 'football', 'basketball'))
    
    inXDF <- tempfile( pattern = ".rxFactors1", fileext = ".xdf")
    rxDataStep(DF, inXDF, overwrite = TRUE) 
    outXDF <-  XDF <- tempfile( pattern = ".rxFactors2", fileext = ".xdf")
    inDS <- RxXdfData(inXDF)
    outDS <- RxXdfData(outXDF)
    
    factorInfo <- list(newSex = list(newLevels = c(M = "Male", F = "Female"), varName = "sex"),
                       age    = list(levels = c(12, 15, 20)),
                       sport  = list(newLevels = list(Summer = c("tennis", "golf"), Winter = c("football","basketball"))))

    reportProgress <- verbose <- 0L
                
    # XDF -> XDF
    xdf.xdf <- rxFactors(inXDF, factorInfo, outFile = outXDF, overwrite = TRUE, 
                         reportProgress = reportProgress, verbose = verbose)
    xdf.xdf.df <- rxDataStep(outXDF)
            
    # XDF -> DF
    xdf.df <- rxFactors(inXDF, factorInfo, outFile = NULL, 
                        reportProgress = reportProgress, verbose = verbose)
    
    # DF -> XDF
    df.xdf <- rxFactors(DF, factorInfo, outFile = outXDF, overwrite = TRUE, 
                        reportProgress = reportProgress, verbose = verbose)
    df.xdf.df <- rxDataStep(outXDF)
    
    # DF -> DF
    df.df <- rxFactors(DF, factorInfo, 
                       reportProgress = reportProgress, verbose = verbose)
    
    # DS -> DS
    ds.ds <- rxFactors(inDS, factorInfo, outFile = outDS, overwrite = TRUE, 
                         reportProgress = reportProgress, verbose = verbose)
    ds.ds.df <- rxDataStep(outDS)
            
    # DS -> DF
    ds.df <- rxFactors(inDS, factorInfo, outFile = NULL, 
                        reportProgress = reportProgress, verbose = verbose)
    
    # DF -> DS
   
    df.ds <- rxFactors(DF, factorInfo, outFile = outDS, overwrite = TRUE, 
                        reportProgress = reportProgress, verbose = verbose)
    df.ds.df <- rxDataStep(outDS)
    
    # DS -> XDF
    ds.xdf <- rxFactors(inDS, factorInfo, outFile = outXDF, overwrite = TRUE, 
                        reportProgress = reportProgress, verbose = verbose)
    ds.xdf.df <- rxDataStep(outXDF)
    
    # XDF -> DS
    xdf.ds <- rxFactors(inXDF, factorInfo, outFile = outDS, overwrite = TRUE, 
                        reportProgress = reportProgress, verbose = verbose)
    xdf.ds.df <- rxDataStep(outDS)
    
    standardDF <- data.frame(sex = DF[["sex"]],
                             age = factor(DF[["age"]], levels = c(12, 15, 20)),
                             sport = factor(c("Summer", "Summer", "Winter", "Winter"), levels = c("Summer", "Winter")),
                             newSex = factor(c("M","M","F","M"), levels = c("M","F")))
    
    checkEquals(df.df, standardDF)
    checkEquals(xdf.xdf.df, standardDF)
    checkEquals(xdf.df, standardDF)
    checkEquals(df.xdf.df, standardDF)
    checkEquals(ds.ds.df, standardDF)
    checkEquals(df.ds.df, standardDF)
    checkEquals(ds.xdf.df, standardDF)
    checkEquals(xdf.ds.df, standardDF)
    checkEquals(ds.ds.df, standardDF)
	file.remove(inXDF)
	file.remove(outXDF)
}

###
# factorInfo fields

"test.rxFactors.args.factorInfo.indexMap.from.newLevels" <- function()
{
    set.seed(100)
    size <- 10
    months <- factor(sample(month.name, size = size, replace = TRUE), levels = month.name)
    DF <- data.frame(Month = months)

    Q1 <- month.name[1:3]
    Q2 <- month.name[4:6]
    Q3 <- month.name[7:9]
    Q4 <- month.name[10:12]

    # newLevels = Q2 Q1 Q4 Q3
    # indexMap  = c( 2, 2, 2, 1, 1, 1, 4, 4, 4, 3, 3, 3 )
    factorInfo <- list(Month = list(newLevels = list(Q2 = Q2, Q1 = Q1, Q4 = Q4, Q3 = Q3), sortLevels = FALSE))
    autoIndexMap <- rxFactors(DF, factorInfo, varsToKeep = "Month")
    factorInfo[["Month"]][["indexMap"]] <- c( 2, 2, 2, 1, 1, 1, 4, 4, 4, 3, 3, 3 )
    manualIndexMap <- rxFactors(DF, factorInfo, varsToKeep = "Month")
    checkEquals(levels(autoIndexMap[["Month"]]), names(factorInfo[["Month"]][["newLevels"]]))
    checkEquals(autoIndexMap, manualIndexMap)

    # newLevels = Q3 Q1 Q2 Q4
    # indexMap  = c( 2, 2, 2, 3, 3, 3, 1, 1, 1, 4, 4, 4 )
    factorInfo <- list(Month = list(newLevels = list(Q3 = Q3, Q1 = Q1, Q2 = Q2, Q4 = Q4), sortLevels = FALSE))
    autoIndexMap <- rxFactors(DF, factorInfo, varsToKeep = "Month")
    factorInfo[["Month"]][["indexMap"]] <- c( 2, 2, 2, 3, 3, 3, 1, 1, 1, 4, 4, 4 )
    manualIndexMap <- rxFactors(DF, factorInfo, varsToKeep = "Month")
    checkEquals(levels(autoIndexMap[["Month"]]), names(factorInfo[["Month"]][["newLevels"]]))
    checkEquals(autoIndexMap, manualIndexMap)

    # newLevels = Q1 Q2 Q3 Q4
    # indexMap  = c( 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 )
    factorInfo <- list(Month = list(newLevels = list(Q3 = Q3, Q1 = Q1, Q2 = Q2, Q4 = Q4), sortLevels = TRUE))
    autoIndexMap <- rxFactors(DF, factorInfo, varsToKeep = "Month")
    factorInfo[["Month"]][["indexMap"]] <- c( 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 )
    manualIndexMap <- rxFactors(DF, factorInfo, varsToKeep = "Month")
    checkEquals(levels(autoIndexMap[["Month"]]), sort(names(factorInfo[["Month"]][["newLevels"]])))
    checkEquals(autoIndexMap, manualIndexMap)

    # newLevels = Q1 Q2 Q3 Q4
    # indexMap  = c( 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 )
    factorInfo <- list(Month = list(newLevels = list(Q2 = Q2, Q1 = Q1, Q4 = Q4, Q3 = Q3), sortLevels = TRUE))
    autoIndexMap <- rxFactors(DF, factorInfo, varsToKeep = "Month")
    factorInfo[["Month"]][["indexMap"]] <- c( 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 )
    manualIndexMap <- rxFactors(DF, factorInfo, varsToKeep = "Month")
    checkEquals(levels(autoIndexMap[["Month"]]), sort(names(factorInfo[["Month"]][["newLevels"]])))
    checkEquals(autoIndexMap, manualIndexMap)
}

"test.rxFactors.args.factorInfo.otherLevel" <- function()
{
    DF <- data.frame(alphabet = factor(rep(letters, each = 3)))
    newLevels <- c(A = "a", B = "b", C = "c")
    originalLevels <- levels(DF[["alphabet"]])

    # Recode a subset of levels, recategorizing all other levels into an "Other" category
    factorInfo <- list(alphabet = list(newLevels = newLevels, otherLevel = "Other"))
    newDF <- rxFactors(DF, factorInfo)
    checkEquals(levels(newDF[["alphabet"]]), c("A", "B", "C", "Other"))

    # Recode a subset of levels, leaving the other levels alone 
    factorInfo <- list(alphabet = list(newLevels = newLevels, otherLevel = NULL))
    newDF <- rxFactors(DF, factorInfo)
    checkEquals(levels(newDF[["alphabet"]]), c("A", "B", "C", originalLevels[-(1:3)]))

    # Test default setting of otherLevel
    factorInfo <- list(alphabet = list(newLevels = newLevels, otherLevel = "Other"))
    newDF <- rxFactors(DF, factorInfo, otherLevel = "CommonOther")
    checkEquals(levels(newDF[["alphabet"]]), c("A", "B", "C", "Other"))

    factorInfo <- list(alphabet = list(newLevels = newLevels))
    newDF <- rxFactors(DF, factorInfo, otherLevel = "CommonOther")
    checkEquals(levels(newDF[["alphabet"]]), c("A", "B", "C", "CommonOther"))
}

"test.rxFactors.args.indexMap.collapse.comparison.to.newLevel.named.collapse" <- function()
{
    surveyDF <- rxDataStep(file.path(rxGetOption("sampleDataDir"), "CustomerSurvey.xdf"))
    sl <- levels(surveyDF[[1]]) 
    DF1 <- rxFactors(inData = surveyDF, 
                factorInfo = list(Q1 = list(newLevels = list( 
                                   "Largely Satisfied" = sl[1:2], 
                                   "Neither Satisfied Nor Dissatisfied" = sl[3:5], 
                                   "Largely Dissatisfied" = sl[6:7]))))
                                            
    DF2 <- rxFactors(inData = surveyDF, 
      factorInfo = list( 
            Q1 = list(newLevels = c("Largely Satisfied", 
                                    "Neither Satisfied Nor Dissatisfied", 
                                    "Largely Dissatisfied"), 
                      indexMap = c(1,1,2,2,2,3,3)))) 

    checkEquals(DF1, DF2)
}

"test.rxFactors.args.factorInfo.nonfactor.name.conversion.specification" <- function()
{
    inXDF <- file.path(rxGetOption("sampleDataDir"), "CensusWorkers.xdf")
    outXDF <-  tempfile( pattern = ".rxFactors3", fileext = ".xdf")
    
    #      age   incwage     perwt       sex  wkswork1     state 
    #"integer" "integer" "integer"  "factor" "integer"  "factor"
    factorInfo <- c("age", "wkswork1")
    rxFactors(inXDF, factorInfo, outFile = outXDF, overwrite = TRUE, varsToKeep = factorInfo)
    newDF <- rxDataStep(outXDF, numRows = 10L)
    checkTrue(is.factor(newDF[["age"]]))
    checkTrue(is.factor(newDF[["wkswork1"]]))
	file.remove(outXDF)
}

"test.rxFactors.args.factorInfo.nonfactor.sortLevels.TRUE" <- function()
{
    DF <- data.frame(foo = 11:1, myVar = c(2, 2, 3, 1, 5, 4, 10, 8, 6, 5, 7))
    factorInfoSortTRUE <- list(myVar = list(sortLevels = TRUE))
    factorInfoSortFALSE <- list(myVar = list(sortLevels = FALSE))
    
    sortedDF <- rxFactors(DF, factorInfoSortTRUE, verbose = 1)
    unsortedDF <- rxFactors(DF, factorInfoSortFALSE)
    
    checkEquals(levels(sortedDF[["myVar"]]), sort(as.character(unique(DF[["myVar"]]))))
    checkEquals(levels(unsortedDF[["myVar"]]), as.character(unique(DF[["myVar"]])))
}

"test.rxFactors.args.factorInfo.nonfactor.overwrite" <- function()
{
    # fix for RA-4214
    DF <- data.frame(myVar1 = 1:5,
                     myVar2 = 5:1,
                     myFac = factor(5:1, levels = c(2, 1, 3, 4, 5)))
    XDF <-  tempfile( pattern = ".rxFactors4", fileext = ".xdf")
    rxDataStep(DF, XDF, overwrite = TRUE)
    
    # bad because we are not renaming non-factor variables during conversion
    badFactorInfo <- list("myVar1", "myVar2", myFac = list(sortLevels = TRUE))
    
    # good because we are renaming non-factor variables during conversion
    goodFactorInfo <- list(myNewVar1 = list(varName = "myVar1"), 
                          myNewVar2 = list(varName = "myVar2"), 
                          myFac = list(sortLevels = TRUE))
                    
    checkException(rxFactors(XDF, outFile = XDF, badFactorInfo, overwrite = TRUE), silent = TRUE)
    z <- rxFactors(XDF, outFile = XDF, goodFactorInfo, overwrite = TRUE)
    checkTrue(inherits(z, "RxXdfData"))
    df.df <- rxFactors(DF, goodFactorInfo)
    xdf.df <- rxDataStep(XDF)
    checkEquals(df.df, xdf.df)
	file.remove(XDF)
}

"test.rxFactors.args.factorInfo.levels.newLevels.otherLevel.nonfactor" <- function()
{
    DF <- data.frame(x = 1:10)
    inXDF <-  tempfile( pattern = ".rxFactors4", fileext = ".xdf")
    outXDF <-  tempfile( pattern = ".rxFactors5", fileext = ".xdf")
    rxDataStep(DF, inXDF, overwrite = TRUE)
    myLevels <- 1:3
    myLevelsChar <- as.character(myLevels)
    
    # data frame
    checkEquals(levels(rxFactors(DF, factorInfo = list(x = list(levels = myLevels, otherLevel = "foo")))[["x"]]), c(myLevelsChar, "foo"))    
    checkEquals(levels(rxFactors(DF, factorInfo = list(x = list(levels = myLevels, otherLevel = NULL)))[["x"]]), myLevelsChar)  
    checkException(rxFactors(DF, factorInfo = list(x = list(levels = myLevels, newLevels = c("cow", "horse"), otherLevel = "pig"))), silent = TRUE)
    checkEquals(levels(rxFactors(DF, factorInfo = list(x = list(levels = myLevels, newLevels = c("cow", "horse", "chicken"), otherLevel = "pig")))[["x"]]), 
        c("cow", "horse", "chicken", "pig"))

    # .xdf
    z <- rxFactors(inXDF, factorInfo = list(x = list(levels = myLevels, otherLevel = "foo")), outFile = outXDF, overwrite = TRUE)
    checkTrue(inherits(z, "RxXdfData"))
    checkEquals(levels(rxDataStep(outXDF)[["x"]]), c(myLevelsChar, "foo"))
    checkEquals(levels(rxDataStep(z)[["x"]]), c(myLevelsChar, "foo"))

    z <- rxFactors(inXDF, factorInfo = list(x = list(levels = myLevels, otherLevel = NULL)), outFile = outXDF, overwrite = TRUE)
    checkTrue(inherits(z, "RxXdfData"))
    checkEquals(levels(rxDataStep(outXDF)[["x"]]), c(myLevelsChar))
    checkEquals(levels(rxDataStep(z)[["x"]]), c(myLevelsChar))

    checkException(rxFactors(inXDF, factorInfo = list(x = list(levels = myLevels, newLevels = c("cow", "horse"), otherLevel = "pig")), 
        outFile = outXDF, overwrite = TRUE), silent = TRUE)
    
    z <- rxFactors(inXDF, factorInfo = list(x = list(levels = myLevels, newLevels = c("cow", "horse", "chicken"), otherLevel = "pig")), 
        outFile = outXDF, overwrite = TRUE)
    checkTrue(inherits(z, "RxXdfData"))
    checkEquals(levels(rxDataStep(outXDF)[["x"]]), c("cow", "horse", "chicken", "pig"))
    checkEquals(levels(rxDataStep(z)[["x"]]), c("cow", "horse", "chicken", "pig"))

    if (file.exists(inXDF)) unlink(inXDF)
    if (file.exists(outXDF)) unlink(outXDF)
}

"test.rxFactors.args.factorInfo.nonfactor.hi.low.remain" <- function()
{
    DF <- data.frame(x = 1:3, alpha = letters[1:3])
    inXDF <-  tempfile( pattern = ".rxFactors5", fileext = ".xdf")
    rxDataStep(DF, inXDF, overwrite = TRUE) 
    outXDF <-  tempfile( pattern = ".rxFactors6", fileext = ".xdf")

    rxFactors(inData = inXDF, outFile = outXDF, overwrite = TRUE, 
              factorInfo = list(alpha = list(newLevels = c(A = "a", B = "b")))) 

    # If the hi/lo information for variable x is NA/NA, you are seeing the bug	
    xVar <- rxGetVarInfo(outXDF)[["x"]]
    checkEquals(xVar[["low"]], 1L)
    checkEquals(xVar[["high"]], 3L)
        
    if (file.exists(inXDF)) unlink(inXDF)
    if (file.exists(outXDF)) unlink(outXDF)
}

"test.rxFactors.args.factorInfo.unsupported.field.names" <- function()
{
    DF <- data.frame(sex = c('Male', 'Male', 'Female', 'Male'), 
	                 age = factor(c(20, 20, 12, 15)), 
	                 sport = c('tennis', 'golf', 'football', 'basketball'))

    factorInfo <- list(
        sex = list(newLevels = c(male = "Male", female = "Female"), rooster = "hen"),
	    age = list(newLevels = list(Young = c("12","15"), Old = "20")),
	    TeamSport = list(newLevels = list(individual = c('tennis', 'golf'), team = c('football', 'basketball')),
                     varName = "sport", cow = "jersey", horse = "palimino")
        )
            
	checkException(rxFactors(DF, factorInfo), silent = TRUE)
}
"test.rxFactors.args.xdfCompressionLevel" <- function()
{
	testXdf <- file.path(rxGetOption("unitTestDataDir"), "test100r5b.xdf")
	testNewXdf <- tempfile(pattern = ".rxFactorTest2", fileext = ".xdf") 
	testCopyXdf <- tempfile(pattern = ".rxFactorTest2", fileext = ".xdf") 
	file.copy(from = testXdf, to = testCopyXdf, copy.mode = FALSE)
	testDataFrame <- rxDataStep(testXdf) 
	
	# Case 1: xdf in, same xdf out
	rxCompressXdf(inFile = testCopyXdf, xdfCompressionLevel = 1, overwrite = TRUE)
	output1 <- rxFactors(inData = testCopyXdf, outFile = testCopyXdf, 
		sortLevels = TRUE,
		factorInfo= c("xfac1", "xfac2"), overwrite = TRUE, xdfCompressionLevel = 1)
	varInfo1 <- rxGetVarInfo( output1 )	
	checkEquals(varInfo1$xfac1$levels, sort(levels(testDataFrame$xfac1)))
	checkEquals(varInfo1$xfac2$levels, sort(levels(testDataFrame$xfac2)))
	
    fileSize1 <- file.info(testCopyXdf)$size 
    
   	file.copy(from = testXdf, to = testCopyXdf, overwrite = TRUE, copy.mode = FALSE)
	rxCompressXdf(inFile = testCopyXdf, xdfCompressionLevel = 1, overwrite = TRUE)
	output2 <- rxFactors(inData = testCopyXdf, outFile = testCopyXdf, 
		sortLevels = TRUE,
		factorInfo= c("xfac1", "xfac2"), overwrite = TRUE, xdfCompressionLevel = 9)
	varInfo2 <- rxGetVarInfo( output2 )	
	checkEquals(varInfo2$xfac1$levels, sort(levels(testDataFrame$xfac1)))
	checkEquals(varInfo2$xfac2$levels, sort(levels(testDataFrame$xfac2)))	
	fileSize2 <- file.info(testCopyXdf)$size 
    checkTrue(fileSize1 > fileSize2)
    	
	
	# Case 2: xdf in, different xdf out
	output3 <- rxFactors(inData = testXdf, outFile = testNewXdf, 
		sortLevels = TRUE,
		factorInfo= c("xfac1", "xfac2"), xdfCompressionLevel = 0)
	varInfo3 <- rxGetVarInfo( output3 )
	checkEquals(varInfo3$xfac1$levels, sort(levels(testDataFrame$xfac1)))
	checkEquals(varInfo3$xfac2$levels, sort(levels(testDataFrame$xfac2)))
	fileSize3 <- file.info(testNewXdf)$size 
	file.remove(testNewXdf)
	
	output4 <- rxFactors(inData = testXdf, outFile = testNewXdf, 
		sortLevels = TRUE,
		factorInfo= c("xfac1", "xfac2"), xdfCompressionLevel = 1)
	varInfo4 <- rxGetVarInfo( output4 )
	checkEquals(varInfo4$xfac1$levels, sort(levels(testDataFrame$xfac1)))
	checkEquals(varInfo4$xfac2$levels, sort(levels(testDataFrame$xfac2)))
	fileSize4 <- file.info(testNewXdf)$size 
    checkTrue(fileSize3 > fileSize4)
	
	file.remove(testCopyXdf)
	file.remove(testNewXdf)
	rm(output1)
	rm(output2)
	rm(output3)
	rm(output4)
}