/*
 * limited emulation of fcntl
 *
 * ++jrb	bammi@cadence.com
 */

#include <fcntl.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>

#ifdef __STDC__
int fcntl (int f, int cmd, ...)
#else
int fcntl (f, cmd)
int f;
int cmd;
#endif
{
    int handle;
    va_list argp;

    va_start(argp, cmd);

    /* check for valid descriptor */
    handle = __OPEN_INDEX(f);
    if( (handle >= __NHANDLES) || (handle < 0) )
    {
	errno = EBADF;
	return -1;
    }
	
    if(__open_stat[handle].status == FH_UNKNOWN)
	isatty(f); /* try to set .status */

    if((__open_stat[handle].status == FH_UNKNOWN) ||
      ((__open_stat[handle].status == FH_ISAFILE) && (__open_stat[handle].filename == (char *)0)) )
    {
	errno = EBADF;
	return -1;
    }

    switch(cmd) {
      case F_DUPFD:
	/* there is no way to emulate this even reasonably under TOS,  so... */
	return dup(f);

      case F_GETFD:
	return (int) (__open_stat[handle].eclose);

      case F_SETFD:
	__open_stat[handle].eclose = va_arg(argp, int) & 1;
	return 0;

      case F_GETFL: /* fudge city */
	return (int)(*((short *)(&(__open_stat[handle]))));

      case F_SETFL:
	*((short *)(&(__open_stat[handle]))) = va_arg(argp, int);
	return 0;

      default:
	errno = EBADARG;
	return -1;
    }
}
