/* Copyright (C) 2000 DJ Delorie, see COPYING.DJ for details */
/* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
/* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
#ifdef __DJGPP__

#include <libc/stubs.h>
#include <unistd.h>
#include <fcntl.h>
#include <dpmi.h>
#include <errno.h>
#include <io.h>
#include <libc/dosio.h>
#include <sys/fsext.h>

int
dup2(int fd, int newfd)
{
  __dpmi_regs r;
  __FSEXT_Function *func, *func_newfd;

  if (fd == newfd)
    return newfd;

  /* Run FSEXT for 'newfd'.  */
  func_newfd = __FSEXT_get_function(newfd);
  if (func_newfd)
  {
#if 1
    int errno_save = errno;
    close (newfd);
    errno = errno_save;
#else
    int rv, errno_save;
    errno_save = errno;
    func(__FSEXT_close, &rv, &newfd);
    errno = errno_save;
#endif
  }

  func = __FSEXT_get_function(fd);
  if (func)
  {
    int rv;
    if (func(__FSEXT_dup2, &rv, &fd))
      return rv;
  }

  __file_handle_set(newfd, __file_handle_modes[fd] ^ (O_BINARY|O_TEXT));
  r.h.ah = 0x46;
  r.x.bx = fd;
  r.x.cx = newfd;
  __dpmi_int(0x21, &r);
  if (r.x.flags & 1)
  {
    errno = __doserr_to_errno(r.x.ax);
    return -1;
  }
  setmode(newfd, __file_handle_modes[fd]);
  return newfd;
}
#endif

