/* dup.c (emx+gcc) -- Copyright (c) 1992-1996 by Eberhard Mattes */

#include <io.h>
#include <errno.h>
#include <emx/io.h>
#include <emx/syscalls.h>

int _dup (int handle)
{
  int new, *pflags1, *pflags2, *pla1, *pla2;

  if ((pflags1 = _fd_flags (handle)) == NULL
      || (pla1 = _fd_lookahead (handle)) == NULL)
    {
      errno = EBADF;
      return -1;
    }
  new = __dup (handle);
  if (new < 0)
    return new;
  if ((pflags2 = _fd_init (new)) == NULL
      || (pla2 = _fd_lookahead (new)) == NULL)
    {
      __close (new);
      errno = EMFILE;
      return -1;
    }
  *pflags2 = *pflags1;
  *pla2 = *pla1;
  return new;
}
