/* telltext.c (emx+gcc) */

/* Test ftell() for text-mode streams.  This program assumes that
   newline is represented by two characters in files and that ftell()
   uses the file positions of the underlying binary file.  That
   assumption is not portable. */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void usage (void)
{
  fprintf (stderr, "Usage: telltext [-u] <input_file> [<output_file>]\n");
  exit (1);
}


int main (int argc, char *argv[])
{
  const char *inp_fname, *out_fname;
  FILE *inp_file, *out_file;
  long count;
  int i, c, unix;

  unix = 0; i = 1;
  if (i < argc && strcmp (argv[i], "-u") == 0)
    unix = 1, ++i;

  if (argc - i < 1 || argc - i > 3)
    usage ();

  inp_fname = argv[i+0];
  if (argc == 3)
    out_fname = argv[i+1];
  else
    out_fname = NULL;

  inp_file = fopen (inp_fname, "r");
  if (inp_file == NULL)
    {
      perror (inp_fname);
      exit (2);
    }

  if (out_fname != NULL)
    {
      out_file = fopen (out_fname, "w");
      if (out_file == NULL)
        {
          perror (out_fname);
          exit (2);
        }
    }
  else
    out_file = NULL;

  count = 0;
  while ((c = fgetc (inp_file)) != EOF)
    {
      if (c == '\n' && !unix)
        count += 2;
      else
        ++count;
      if (out_file != NULL && fputc (c, out_file) == EOF)
        {
          perror (out_fname);
          exit (2);
        }
      if (ftell (inp_file) != count)
        {
          fprintf (stderr, "ftell() mismatch on input file: %ld vs. %ld\n",
                   ftell (inp_file), count);
          exit (2);
        }
      if (out_file != NULL && ftell (out_file) != count)
        {
          fprintf (stderr, "ftell() mismatch on output file: %ld vs. %ld\n",
                   ftell (out_file), count);
          exit (2);
        }
    }

  if (ferror (inp_file) || fclose (inp_file) != 0)
    {
      perror (inp_fname);
      exit (2);
    }
  if (out_file != NULL)
    {
      if (ferror (out_file) || fclose (out_file) != 0)
        {
          perror (out_fname);
          exit (2);
        }
    }
  return 0;
}
