#include <errno.h>
#include <fcntl.h>
#include <limits.h>

int _dup2(int filedes, int filedes2)
{
  int status;

  /* First make sure that filedes points to an open file */

  status = _fcntl(filedes, F_GETFL);
  if(status == -1) return -1;

  if(filedes2 > OPEN_MAX) {
    errno = EBADF;
    return -1;
  };

  /* If we already have this open, just return it */
  if(filedes == filedes2) return filedes;

  /* Now see if filedes2 is open. */
  status = _fcntl(filedes2, F_GETFL);
  if(status != -1) {
    /* Really we need to check and see if filedes2 points to the same
       file as filedes, but it does not matter that much */
    _close(filedes2);
  };

  /* Now duplicate the fd and return. */
  status = _fcntl(filedes, F_DUPFD, filedes2);

  if(status != filedes2) {
    _close(status);
    errno = EBADF;
    return -1;
  }

  status = _fcntl(filedes2, F_SETFD, 0);
  return status;
}

#ifdef ELF_LIBRARY
__asm__(".weak dup2; dup2 = _dup2");
#endif
