/* from the original GCC TOS library by jrd */
/* this algorithm is due to Allan Pratt @ Atari.  Thanks Allan! */

#include <errno.h>
#include <osbind.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <device.h>

int isatty(fd)
int fd;
{
  int rc;
  long oldloc, seekval;
  int handle = __OPEN_INDEX(fd);
  struct _device *dev;

  if ((short)handle < 0)
	return(1);

  dev = _dev_fd(fd);
  if (dev && ((dev->open) || (dev->dev == 0xfffd)))
  {	/* a special device or PRN: */
      return 0;
  }
  
  if (handle < __NHANDLES)
	if (__open_stat[handle].status != FH_UNKNOWN)
		return(__open_stat[handle].status == FH_ISATTY);
  oldloc = Fseek (0L, fd, SEEK_CUR);	/* seek zero bytes from current loc */
  if ((seekval = Fseek (1L, fd, SEEK_SET)) != 0) /* try to seek ahead one byte */
    if ((seekval > 0) || (seekval == ((long)(-EBADARG)))) /* out of range... */
      rc = 0;			/* file, not a tty */
    else 
      {
      errno = EBADF;		/* any other error returns "invalid handle" */
				/* because you can't tell */
      rc = 0;
      }
  else
    rc = 1;			/* yes, tty (Fseek returns 0 only for ttys) */
  (void)Fseek(oldloc, fd, SEEK_SET);	/* seek back to original location */
  if (handle < __NHANDLES)
	if (rc)
		__open_stat[handle].status = FH_ISATTY;
	    else
		__open_stat[handle].status = FH_ISAFILE;
  return (rc);			/* return true, false, or error */
}
