###
### write_kfamset
###
### dependencies: kst, kstMatrix, MASS, openxlsx2, readODS, tools
###

write_kfamset <- function (x, filename, format=NULL, sep=',', enforce = TRUE) {
  if (inherits(x, "kfamset")) {
    mat <- as.binaryMatrix(x)
    enforce <- FALSE
  } else if (inherits(x, "kmfamset")) {
    enforce <- FALSE
    mat <- x
  }
  else {
    mat <- x
    if (enforce)
      warning(sprintf("Attempt to store '%s' object as 'kmfamset'. Famset determination is enforced.", class(mat)[1]))
    else
      warning(sprintf("Storing '%s' object as Famset", class(mat)[1]))
    if (!inherits(mat, "matrix"))
      stop("'x' must be a matrix.")
  }
  if (enforce) mat <- kmfamset(mat)
  
  ext <- file_ext(filename)
  if (is.null(format)) {
    if (ext == "csv") format <- "CSV"
    else if (ext == "xlsx") format <- "XLSX"
    else if (ext == "ods") format <- "ODS"
    else format <- "KST"
  } else {
    if ((ext == "csv") && (format != "CSV"))
      warning(sprintf('Storing file in "%s" format in .csv file!', format))
    else if ((ext == "ods") && (format != "ODS"))
      warning(sprintf('Storing file in "%s" format in .ods file!', format))
    else if ((ext == "xlsx") && (format != "XLSX"))
      warning(sprintf('Storing file in "%s" format in .xlsx file!', format))
    else if (format %in% c("CSV", "ODS", "XLSX") && tolower(format) != ext)
      warning(sprintf("Format specification '%s' and filename extension '%s' do nto fit together!",
                      format, ext))
  }
  
  size <- dim(mat)
  
  if (format == "CSV") {
    if (sep == ',') dec <- '.'
    else dec <- ','
    if (is.null(colnames(mat)))
      write.table(mat, filename, sep=sep, row.names=FALSE, col.names=FALSE)
    else
      write.table(mat, filename, sep=sep, row.names=FALSE, col.names=TRUE)
  } else if (format == "XLSX") {
    if (is.null(colnames(mat)))
      write_xlsx(as.data.frame(mat), file = filename, col.names=FALSE)
    else write_xlsx(as.data.frame(mat), file = filename)
  } else if (format == "ODS") {
    if (is.null(colnames(mat)))
      write_ods(as.data.frame(mat), path = filename, col_names=FALSE)
    else write_ods(as.data.frame(mat), path = filename)
  } else {
    con <- file(filename)
    if (is.null(con))
      stop(sprintf("Unable to open file %s.", dQuote(filename)))
    open(con, open="w")
    
    if (format == "KST") {
      cat(sprintf("%d\n", size[2]), file=con)
      cat(sprintf("%d\n", size[1]), file=con)
    }
    else {
      close(con)
      unlink(filename)
      stop(sprintf("Famset file must have format %s or %s.",
                   dQuote("KST"),
                   "spreadsheet format"
      ))
    }
    
    colnames(mat) <- NULL
    write.table(mat, sep="", file=con, col.names=FALSE, row.names=FALSE)
    
    close(con)
  }
}
