# define PRIVATE static
# define PUBLIC 

#ifndef TRUE
# define TRUE  1
# define FALSE 0
#endif

#include <stdio.h>
#include <sys/fcntl.h>
#include <sys/errno.h>
extern int errno;

PUBLIC void
setblock (fd, on)
    int fd;
    int on;
{
  static int blockf, nonblockf;
  static int first= TRUE;
  int flags;

  if (first) {
    first= FALSE;
    if  ((flags= fcntl (fd, F_GETFL, 0)) == -1) {
      perror ("fcntl");
      exit (1);
    }
    blockf= flags & ~O_NDELAY;
    nonblockf= flags | O_NDELAY;
  }
  if (fcntl (fd, F_SETFL, on ? blockf : nonblockf) == -1) {
    perror ("fcntl/2");
    exit (1);
  }
}

PRIVATE char cbuf[20]= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
PUBLIC int
cready (fd)
    int fd;
{
  int n;

  if (cbuf[fd] != 0)
    return TRUE;
  setblock (fd, FALSE);
  n= read (fd, cbuf+fd, 1);
  setblock (fd, TRUE);
  if (n < 0 && errno != EWOULDBLOCK) {
    perror ("while reading");
    exit (1);
  }
  if (0 < n)
    return TRUE;
  else {
    cbuf[fd]= 0;
    return FALSE;
  }
}

PUBLIC int
cget (fd)
    int fd;
{
  char c;

  if (cbuf[fd] != 0) {
    c= cbuf[fd];
    cbuf[fd]= 0;
    return (c & 0377);
  }
  switch (read (fd, cbuf+fd, 1)) {
  case -1:
    perror ("read");
    exit (1);
  case 0:
    return (EOF);
  default:
    c= cbuf[fd];
    cbuf[fd]= 0;
    return (c & 0377);
  }
}
