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

#include <stdio.h>
#include <io.h>
#include <sys/ioctl.h>
#define INCL_DOSFILEMGR
#include <os2.h>

int main (int argc, char *argv[])
{
  ULONG rc, action;
  HFILE hf;
  int i, fd, noimp, ht;

  i = 1; noimp = 0;
  if (i < argc && strcmp (argv[i], "-n") == 0)
    noimp = 1, ++i;
  if (argc - i != 1)
    {
      fputs ("Usage: imphandl <filename>\n", stderr);
      return 1;
    }

  rc = DosOpen (argv[i], &hf, &action, 0, 0,
                OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW,
                OPEN_ACCESS_READONLY | OPEN_SHARE_DENYNONE, NULL);
  if (rc != 0)
    {
      fprintf (stderr, "DosOpen failed, rc=%lu\n", rc);
      return 2;
    }

  if (noimp)
    fd = hf;
  else
    {
      fd = _imphandle (hf);
      if (fd == -1)
        {
          perror ("_imphandle()");
          return 2;
        }
      printf ("%lu -> %d\n", hf, fd);
    }

  if (ioctl (fd, FGETHTYPE, &ht) < 0)
    {
      perror ("ioctl FGETHTYPE");
      return 2;
    }
  switch (ht)
    {
    case HT_FILE:
      printf ("Regular file\n");
      break;
    case HT_UPIPE:
      printf ("Unnamed pipe\n");
      break;
    case HT_NPIPE:
      printf ("Named pipe\n");
      break;
    case HT_DEV_NUL:
      printf ("Null device\n");
      break;
    case HT_DEV_CON:
      printf ("Console device\n");
      break;
    case HT_DEV_CLK:
      printf ("Clock device\n");
      break;
    case HT_DEV_OTHER:
      printf ("Other device\n");
      break;
    default:
      printf ("UNKNOWN handle type: %d\n", ht);
      break;
    }
  return 0;
}
