/* 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 <ioctl.h>

struct __open_file __open_stat[__NHANDLES];

int isatty(fd)
int fd;
{
  int rc;
  long oldloc, seekval;
  int handle = __OPEN_INDEX(fd);

  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))	/* 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;
		__open_stat[handle].flags = CRMOD|ECHO;
	}
	else
		__open_stat[handle].status = FH_ISAFILE;
  return (rc);			/* return true, false, or error */
}
