.packageName <- "svIO"
"clippaste" <-
function(name = "newobj", type = "ascii", objclass = "data.frame", pos = 1, ...) {
	# There is no readClipboard function outside of Windows... make one!
	### Rem: this is not tested yet. It follows a suggestion by Ted Harding
	if (!.Platform$OS == "windows") {
	    "readClipboard" <- function() {
			File <- tempfile()
			# Paste the content of the clipboard into File
			system(paste("wxpaste >", File), wait = TRUE, invisible = TRUE)  # TO DO: manage errors!
			# Read File and destroy it
			Data <- readLines(File)
			unlink(File)
			# Return results
			return(Data)
	    }
	}

	"clippasteASCII" <- function(name, objclass, pos, ...) {
		# Read clipboard content to create a matrix, a data.frame or a function in R
		# If function, content is sourced
		if (objclass == "function") {
			source(textConnection(readClipboard()))$value
			invisible(return(1))
		}
		tmp <- read.table(textConnection(readClipboard()))
		if (objclass == "matrix") tmp <- as.matrix(tmp)
		expr <- paste("assign('", name, "', tmp, pos=", pos, ")", sep="")
		try(eval(parse(text=expr)))
		invisible(TRUE)
	}

	"clippasteRAW" <- function(name, pos, ...) {
		expr <- paste("assign('", name, "',", paste(readClipboard(), sep="", collapse="\n"), ",pos=", pos, ")", sep="")
		try(eval(parse(text = expr)))
		invisible(TRUE)
	}

	res <- switch(type,
		raw = clippasteRAW(name, pos, ...),
		clippasteASCII(name, objclass, pos, ...))	# If "ASCII" or nomatch
	invisible(res)
}
"copy" <-
function(x, type = "raw", objname = deparse(substitute(x)), ...) {
	objname <- objname
	# Compute the expression
	xexp <- try(if (inherits(x, "expression")) x else NULL, silent = TRUE)
	if (inherits(xexp, "try-error") || is.null(xexp)) {
		xexp <- substitute(x)
		if (is.character(xexp)) # To make sure that non conventional names will be correctly evaluated, we use backticks!
			xexp <- parse(text = paste("`", xexp, "`", sep = ""))
		xexp <- as.expression(xexp)
	}
	# The way to copy to the clipboard is platform-dependent
	if (.Platform$OS == "windows"){ # This is Windows
		export(x = xexp, type = type, file = "clipboard", append = FALSE, objname = objname, ...)
	} else { ### Rem: according to a suggestion by Ted Harding... not tested yet!
		File <- tempfile()
		export(x = xexp, type = type, file = File, append = FALSE, objname = objname, ...)
		system(paste("wxcopy <", File), wait = TRUE, invisible = TRUE) # TO DO: manage errors!
		unlink(File)
	}
}
"export" <-
function(x, type = "raw", file, append = FALSE, objname = deparse(substitute(x)), ...)
	UseMethod("export")
"export.data.frame" <-
function(x, type = "raw", file = NULL, append = FALSE, objname = deparse(substitute(x)), saslib = "work", sasmember = "", writeit = TRUE, ...) {

	"exportASCII" <- function(x, file, append, ...) {
		col1 <- dimnames(x)[[1]]
		for (i in 1:ncol(x)) col1 <- paste(col1, x[, i], sep = "\t")
		col1 <- paste(col1, collapse = "\n")
		row1 <- c("", dimnames(x)[[2]])
		txt <- paste(row1, collapse = "\t")
		txt <- paste(txt, col1, sep = "\n")
		# write code to file connection
		if (file != "") tmpfile <- file(file, c("w","a")[append+1]) else tmpfile <- file
		cat(txt, file = tmpfile, ...)
		if (file != "") close(tmpfile)
		invisible(return(txt))
	}

	"exportSAS" <- function(x, file, append, objname, saslib = "work", sasmember = "",writeit=TRUE, ...) {
		if (sasmember == "") {
			objname <- unlist(strsplit(objname, NULL))
			objname[objname == " "] <- "_"
			objname <- objname[objname %in% c(letters, LETTERS, 0:9, "_")]
			objname <- paste(objname, collapse = "", sep = "")
		}
		else objname <- sasmember
		.SASdatasetname <- objname
		line <- paste("DATA ", saslib, ".", objname, ";", sep = "")
		tmp <- dimnames(x)[[2]]
		# Special treatment for data.frame
		# Remove special characters in variable names
		tmp <- sapply(tmp, FUN = function(x) strsplit(x, NULL))
		tmp <- sapply(tmp, FUN = function(vec) return(vec[vec %in% c(letters, LETTERS, 0:9, "_")]), simplify = FALSE, USE.NAMES = FALSE)
		tmp <- sapply(tmp, FUN = function(vec){
		    if (!vec[1] %in% c(letters, LETTERS)) vec = c("V", vec[2:length(vec)]); return(vec)},
		    simplify = FALSE, USE.NAMES = FALSE)
		SAScolnames <- sapply(tmp, paste, collapse = "")
		line <- c(line, "\t INFILE cards missover;")
		line <- c(line, paste("\t INPUT", paste(SAScolnames, collapse = " "), ";", sep = " "))
		line <- c(line, "\t CARDS;")

		# PROC FORMAT
		.tmpSVline2 <- c("PROC FORMAT;")
		.tmpSVboolformat <- FALSE # Indicates whether format has to be created or not

		# PROC DATASETS
		.tmpSVline3 <- c(paste("PROC DATASETS lib=", saslib , " nolist;", sep = "", collapse = ""))
		.tmpSVline3 <- c(.tmpSVline3, paste("\t MODIFY ", objname, ";", sep = ""))

		# data
		processcolumn <- function(x, varname, i) {
			if (!class(x) %in% c("integer", "numeric")){
				x <- as.factor(as.character(x))
				.tmpSVboolformat <- TRUE
				SASlabels <- levels(x)
				SAScodes <- 1:length(SASlabels)
				tmpcodes <- paste(SAScodes, "=\"", SASlabels, "\"", collapse = "\n", sep="")
				.tmpSVline2 <- c(.tmpSVline2, paste("VALUE V", i, "f", sep = ""))
				.tmpSVline2 <- c(.tmpSVline2, paste(tmpcodes, ";", sep = "\n"))
				.tmpSVline3 <- c(.tmpSVline3, paste("\t FORMAT ", varname, " V", i, "f.;", sep = ""))
				x <- as.numeric(x)
			}
			x <- as.character(x)
			x[is.na(x)] <- "."
			return(x)
		}
		col1 <- paste("\t", processcolumn(x[, 1], SAScolnames[1], 1))
		if (dim(x)[2] > 1) {
			for (i in 2:dim(x)[2]) col1 <- paste(col1, processcolumn(x[, i], SAScolnames[i], i), sep = "\t")
			col1 <- paste(col1, collapse = "\n")
		}
		# DATASTEP
		line <- c(line, col1)
		line <- c(line, ";")
		line <- c(line, "RUN;\n")

		if (.tmpSVboolformat){
			# PROC FORMAT
			.tmpSVline2 <- c(.tmpSVline2, "RUN;")
			# PROC DATASETS
			.tmpSVline3 <- c(.tmpSVline3, "RUN;\nQUIT;")
			line <- c(line, "\n", .tmpSVline2, "\n", .tmpSVline3)
		}
		rm(list = c(".tmpSVline2", ".tmpSVline3", ".tmpSVboolformat"), pos = 1)

		# write code to file connection
		if (writeit==TRUE){
			line <- paste(line, collapse = "\n")
			if (file != "") tmpfile <- file(file, c("w", "a")[append + 1]) else tmpfile <- file
			cat(line, file = tmpfile, append = append, ...)
			if (file != "") close(tmpfile)
		}
		invisible(return(line))
	}

	if (is.null(file) || file == "clipboard") append = FALSE # Make sure we do not append to the clipboard!
	objname <- objname
	# Compute the expression
	xexp <- try(if (inherits(x, "expression")) x else NULL, silent = TRUE)
	if (inherits(xexp, "try-error") || is.null(xexp)) {
		xexp <- substitute(x)
		if (is.character(xexp)) # To make sure that non conventional names will be correctly evaluated, we use backticks!
			xexp <- parse(text=paste("`", xexp, "`", sep = ""))
		xexp <- as.expression(xexp)
	}
	# Do we have to pass this to a custom function as 'export.data.frame..type()'?
	custom <- paste("export.data.frame..", type, sep = "")
	if (exists(custom, mode = "function")) {
		res <- get(custom, mode = "function")(expr = xexp, objname = objname, file = file, append = append, ...)
	} else {	
		# Process the command in the standard function 
		x <- eval(xexp, envir = .GlobalEnv)
        # Done in NAMESPCE
        #require(svMisc)
        res <- switch(type,
			"typelist"= unique(c("raw", "ascii", "html", "latex", "sascode", listCustoms("export", "data.frame"))),
			"ascii"   = exportASCII(x, file, append, ...),
			"sascode" = exportSAS(x, file, append, objname, saslib, sasmember, writeit, ...),
			export.default(x = xexp, type = type, file = file, append = append, ...))
	}
	if (type == "typelist") return(res) else invisible(res)
}
"export.default" <-
function(x, type = "raw", file, append = FALSE, objname = deparse(substitute(x)), ...) {

	"exportHTML" <- function(x, file, append, ...) {
        # Done in NAMESPACE
        #require(svMisc)
        #Require(R2HTML)
		if (file != "") tmpfile <- file(file, c("w", "a")[append + 1]) else tmpfile <- file
		HTML(x, file = tmpfile, ...)
		if (file != "") close(tmpfile)
		invisible(return(TRUE))
	}

	"exportLaTeX" <- function(x, file, append, ...) {
        # Done in NAMESPACE
        #require(svMisc)
        if (!(Require(Hmisc)))
			stop("Package HMisc is required for LaTeX exportation!")
		if (file != "") tmpfile <- file(file, c("w", "a")[append+1]) else tmpfile <- file
		latex(x, file = tmpfile, ...)
		if (file != "") close(tmpfile)
		invisible(return(TRUE))
	}

	"exportASCII" <- function(x, file, append, ...) {
		treated <- FALSE
		if (is.vector(x)) {
			txt <- paste(x, collapse = "\t")
			treated <- TRUE
		}
		if (is.matrix(x)) {
			txt <- as.character(x)
			txt <- paste(apply(x, 1, FUN = paste, collapse = "\t"), collapse = "\n")
			treated <- TRUE
		}
		if (!treated) {
			tmpfile <- tempfile()
			sink(tmpfile)
			print(x)
			sink()
			txt <- readLines(tmpfile)
			txt <- paste(txt, collapse = "\n")
		}

		if (file != "") tmpfile <- file(file, c("w", "a")[append+1]) else tmpfile <- file
		cat(txt, file = tmpfile, ...)
		if (file != "") close(tmpfile)
		invisible(return(TRUE))
	}

	"exportRaw" <- function(x, file, ...) {
		if (file != "") tmpfile <- file(file, c("w", "a")[append+1]) else tmpfile <- file
		dput(x, file = tmpfile)
		if (file != "") close(tmpfile)
		invisible(return(TRUE))
	}

	if (is.null(file) || file == "clipboard") append = FALSE # Make sure we do not append to the clipboard!
	objname <- objname
	# Compute the expression
	xexp <- try(if (inherits(x, "expression")) x else NULL, silent = TRUE)
	if (inherits(xexp, "try-error") || is.null(xexp)) {
		xexp <- substitute(x)
		if (is.character(xexp)) # To make sure that non conventional names will be correctly evaluated, we use backticks!
			xexp <- parse(text = paste("`", xexp, "`", sep = ""))
		xexp <- as.expression(xexp)
	}
	# Do we have to pass this to a custom function as 'export.default..type()'?
	custom <- paste("export.default..", type, sep = "")
    # Done in NAMESPACE
    #require(svMisc)
    if (exists(custom, mode = "function")) {
		res <- get(custom, mode = "function")(expr = xexp, objname = objname, file = file, append = append, ...)
	} else {	
		# Process the command in the standard function 
		x <- eval(xexp, envir = .GlobalEnv)
		res <- switch(type,
			"typelist"= unique(c("raw", "ascii", "html", "latex", listCustoms("export", "default"))),
			"html"    = exportHTML(x, file, append, ...),
			"latex"   = exportLaTeX(x, file, append, ...),
			"ascii"   = exportASCII(x, file, append, ...),
			exportRaw(x, file, append, ...))
	}
	if (type == "typelist") return(res) else invisible(res)
}
"export.matrix" <-
function(x, type = "raw", file, append = FALSE, objname = deparse(substitute(x)), ...) {
	if (is.null(file) || file == "clipboard") append = FALSE # Make sure we do not append to the clipboard!
	objname <- objname
	# Compute the expression
	xexp <- try(if (inherits(x, "expression")) x else NULL, silent = TRUE)
	if (inherits(xexp, "try-error") || is.null(xexp)) {
		xexp <- substitute(x)
		if (is.character(xexp)) # To make sure that non conventional names will be correctly evaluated, we use backticks!
			xexp <- parse(text = paste("`", xexp, "`", sep = ""))
		xexp <- as.expression(xexp)
	}
	# Do we have to pass this to a custom function as 'export.matrix..type()'?
	custom <- paste("export.matrix..", type, sep = "")
	if (exists(custom, mode = "function")) {
		res <- get(custom, mode = "function")(expr = xexp, objname = objname, file = file, append = append, ...)
	} else {	
		# Essentially call export.data.frame to ensure columns have names
		res <- export.data.frame(x = xexp, type = type, file = file, append = append, objname = objname, ...)
	}
	if (type == "typelist") return(res) else invisible(res)
}
