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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
#include <fcntl.h>
#include <os2.h>

static int verbose = 0;

static int nstreams (void)
{
  FILE *f;
  int i;

  f = fopen ("nul", "r");
  if (f == NULL)
    {
      if (verbose)
        putchar ('\n');
      return 0;
    }
  if (verbose)
    printf ("%d ", fileno (f));
  i = nstreams () + 1;
  fclose (f);
  return i;
}


static int nhandles (void)
{
  int h, i;

  h = open ("nul", O_RDONLY);
  if (h < 0)
    {
      if (verbose)
        putchar ('\n');
      return 0;
    }
  if (verbose)
    printf ("%d ", h);
  i = nhandles () + 1;
  close (h);
  return i;
}


int main (int argc, char *argv[])
{
  int argi;

  argi = 1;
  if (argi < argc && strcmp (argv[argi], "-v") == 0)
    {
      verbose = 1; ++argi;
    }
  if (_osmode == OS2_MODE)
    {
      LONG req_count;
      ULONG rc, handle_count;

      req_count = 0;
      if (argi + 1 < argc && strcmp (argv[argi], "-s") == 0)
        {
          req_count = atoi (argv[argi+1]);
          argi += 2;
        }
      rc = DosSetRelMaxFH (&req_count, &handle_count);
      if (rc != 0)
        fprintf (stderr, "DosSetRelMaxFH failed, rc=%lu\n", rc);
      else
        printf ("%lu OS/2 file handles\n", handle_count);
    }
  printf ("%d handles\n", nhandles ());
  printf ("%d streams\n", nstreams ());
  return 0;
}
