/*
 * The routines in this file read and write ASCII files from the disk. All of
 * the knowledge about files are here. A better message writing scheme should
 * be used.
 */
#include <stdio.h>
#include "ed.h"

FILE *ffp = NULL;    /* File pointer, all functions. */

/*
 * Open a file for reading.
 */
ffropen(fn)
char *fn;
{
  if ((ffp=fopen(fn, "r")) == NULL)
    return (FIOFNF);
  return (FIOSUC);
}

/*
 * Open a file for writing. Return TRUE if all is well, and FALSE on error
 * (cannot create).
 */
ffwopen(fn)
char *fn;
{
  if ((ffp=fopen(fn,"w")) == NULL) {
#ifdef DEUTSCH
    mlwrite("Fehler beim Öffnen der Ausgabedatei");
#else
    mlwrite("Cannot open file for writing");
#endif
    return (FIOERR);
  }
  return (FIOSUC);
}

/*
 * Close a file. Should look at the status in all systems.
 */
ffclose()
{
  if (ffp != NULL)
    fclose(ffp);

  return (FIOSUC);
}

/*
 * Write a line to the already opened file. The "buf" points to the buffer,
 * and the "nbuf" is its length, less the free newline. Return the status.
 * Check only at the newline.
 */
ffputline(buf, nbuf)
register char buf[];
{
 register int i;

 for (i = 0; i < nbuf; ++i)
  fputc(buf[i]&0xFF, ffp);

 fputc('\n', ffp);

 if (ferror(ffp)) {
#ifdef DEUTSCH
  mlwrite("Schreibfehler!");
#else
  mlwrite("Write I/O error");
#endif
  return (FIOERR);
 }
 return (FIOSUC);
}

/*
 * Read a line from a file, and store the bytes in the supplied buffer. The
 * "nbuf" is the length of the buffer. Complain about long lines and lines
 * at the end of the file that don't have a newline present. Check for I/O
 * errors too. Return status.
 */
ffgetline(buf, nbuf, len)
register char buf[];
register int *len;
{
 register int c;
 register int i;

 i = 0;
 while ((c = fgetc(ffp)) != EOF && c != '\n') {
  buf[i++] = c;
  if (i == nbuf-1) {
#ifdef DEUTSCH
   mlwrite("Datei enthielt überlange Zeilen");
#else
   mlwrite("File had long line");
#endif
   break;
  }
 }

 if (c == EOF) {
  if (ferror(ffp)) {
#ifdef DEUTSCH
  mlwrite("Lesefehler!");
#else
  mlwrite("File read error");
#endif
  return (FIOERR);
  }
  if (i == 0) {
  return (FIOEOF);
  }
 }

 buf[i] = 0;
 *len = i;
 return (FIOSUC);
}
