###
### write_surmisefunction.R
###

write_surmisefunction <- function (x, filename, sep=',') {
  if (!inherits(x, "kmsurmisefunction")) {
    stop(sprintf("%s must be of class %s!",
                 dQuote("x"),
                 dQuote("kmsurmisefunction")
    ))
  }
  
  ext <- tolower(file_ext(filename))
  format <- NULL
  if (ext == "csv") format <- "CSV"
  else if (ext == "xlsx") format <- "XLSX"
  else if (ext == "ods") format <- "ODS"
  else stop("Unknown filename extension.")
  if (format == "CSV") {
    if (sep == ',') dec <- '.'
    else dec <- ','
    if (is.null(colnames(x)))
      write.table(x, filename, sep=sep, row.names=FALSE, col.names=FALSE)
    else
      write.table(x, filename, sep=sep, row.names=FALSE, col.names=TRUE)
  } else if (format == "XLSX") {
    if (is.null(colnames(x)))
      write_xlsx(as.data.frame(x), file = filename, col.names=FALSE)
    else write_xlsx(as.data.frame(x), file = filename)
  } else if (format == "ODS") {
    if (is.null(colnames(x)))
      write_ods(as.data.frame(x), path = filename, col_names=FALSE)
    else write_ods(as.data.frame(x), path = filename)
  }
}
