/* mftest.c */

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <errno.h>

static void usage (void)
{
  fputs ("Usage: mftest [-f] <input_file> <size> <increment>\n", stderr);
  exit (1);
}

int main (int argc, char *argv[])
{
  FILE *in, *mem;
  char buf[128], *str, *p;
  int c, n, inc, opt_f;
  size_t size;
  long x;

  opt_f = 0;
  while ((c = getopt (argc, argv, "f")) != -1)
    switch (c)
      {
      case 'f':
        opt_f = 1;
        break;
      default:
        usage ();
    }
  argc -= optind;
  argv += optind;
  if (argc != 3)
    usage ();
  errno = 0;
  x = strtol (argv[1], &p, 0);
  if (errno != 0 || *p != 0 || x < 0)
    usage ();
  size = (size_t)x;
  x = strtol (argv[2], &p, 0);
  if (errno != 0 || *p != 0)
    usage ();
  inc = (int)x;
  in = fopen (argv[0], "r");
  if (in == NULL)
    {
      perror (argv[0]);
      return 1;
    }
  mem = _mfopen (NULL, "wb", size, inc);
  if (mem == NULL)
    {
      perror ("_mfopen");
      return 1;
    }
  for (;;)
    {
      n = fread (buf, 1, sizeof (buf), in);
      if (n == 0)
        break;
      if (fwrite (buf, 1, n, mem) != n)
        {
          perror ("fwrite");
          return 1;
        }
      if (opt_f)
        fflush (mem);
    }
  fclose (in);
  fprintf (stderr, "%ld characters\n", ftell (mem));
  fputc (0, mem);
  str = _mfclose (mem);
  if (str == NULL)
    fprintf (stderr, "_mclose: NULL\n");
  else
    fputs (str, stdout);
  return 0;
}
