write.mitmlMplus <- function(x, filename, suffix = "list", sep = "\t", dec = ".", na.value=-999){
# write text files that can be read into Mplus

  if(!inherits(x, "mitml") && !inherits(x, "mitml.list")) stop("'x' must be of class 'mitml' or 'mitml.list'.")

  if(inherits(x, "mitml")){
    x <- mitmlComplete(x, "all", force.list = TRUE)
  }
  m <- length(x)

  if(!is.list(x)) x <- list(x)

  dnames <- paste(filename, 1:m, ".dat", sep = "")
  lname <- paste(filename, suffix, ".dat", sep = "")

  write.table(dnames, file = lname, col.names = FALSE, row.names = FALSE, quote = FALSE)

  for(ii in 1:m){

    out <- x[[ii]]
    # convert factors
    notnum <- which(sapply(out, function(z) !is.numeric(z)))
    conv <- as.list(notnum)
    for(nn in notnum){
      out[,nn] <- as.factor(out[,nn])
      conv[[colnames(out)[nn]]] <- matrix(c(levels(out[,nn]), 1:nlevels(out[,nn])), ncol = 2)
      out[,nn] <- as.numeric(out[,nn])
    }
    # write
    out[is.na(out)] <- na.value
    write.table(out, file = dnames[ii], sep = sep, dec = dec, col.names = F, row.names = F,
      quote = FALSE)

  }

  # log file
  cname <- paste(filename, ".log", sep = "")
  cat(file = cname, "The data set featured the following variables:")
  cat(file = cname, "\n\n", paste(colnames(out), collapse = " "), sep = "", append = T)
  if(length(conv)>0){
    cat(file = cname, "\n\n", "Factors were converted to numeric values as follows:\n ", sep = "", append = T)
    for(cc in 1:length(conv)){
      cat(file = cname, "\n", names(conv[cc]), ":\n", sep = "", append = T)
      write.table(conv[[cc]], file = cname, row.names = F, col.names = F, sep = " = ", quote = F, append = T)
    }
  }

  # input file
  iname <- paste(filename, ".inp", sep = "")
  cat(file = iname, sep = "",
    "TITLE:\n  This Mplus input file for multiply imputed data sets was generated by mitml in R.\n",
    "DATA:\n  file = ", lname, ";\n",
    "  type = imputation;\n",
    "VARIABLE:\n  names = ", paste(colnames(out), collapse = " "), ";\n",
    "  missing = all (", na.value, ");"
  )

  invisible()

}

