/* _imphand.c (emx+gcc) -- Copyright (c) 1994-1996 by Eberhard Mattes */

#include <io.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <emx/io.h>
#include <emx/syscalls.h>

int _fmode_bin;

int _imphandle (int handle)
{
  int fd, rc, ht, *pflags;

  if (handle < 0)
    {
      errno = EBADF;
      return -1;
    }

  fd = __imphandle (handle);
  if (fd == -1)
    return -1;
  pflags = _fd_init (fd);
  if (pflags == NULL)
    {
      /* `fd' has been relocated and is now out of range. */

      __dup2 (fd, handle);
      __close (fd);
      errno = EBADF;
      return -1;
    }

  *pflags = O_RDWR;             /* TODO */
  if (_fmode_bin == 0)
    *pflags |= O_TEXT;
  rc = __ioctl1 (fd, 0);
  if (rc != -1 && (rc & 0x80))
    *pflags |= F_DEV;
  rc = __ioctl2 (fd, FGETHTYPE, (int)&ht);
  if (rc >= 0)
    {
      if (HT_ISDEV (ht))
        *pflags |= F_DEV;
      if (ht == HT_UPIPE || ht == HT_NPIPE)
        *pflags |= F_PIPE;
    }
  return fd;
}
