/*  Version Feb 2 1988 */
#define DEBUG 1
typedef enum {FALSE, TRUE} BOOLEAN;
#include <termio.h>
#define lowbyte(w) ((w) & 0377)
#define highbyte(w) lowbyte((w)>>8)
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#ifdef BUFSIZ
#undef BUFSIZ
#endif
#define BUFSIZ 256
#define EMPTY '\0'
static char cbuf=EMPTY;
static struct termio tbufsave;
BOOLEAN cready()
{
	int c;
	c = (int)cbuf;
	if (c != EMPTY)
		return(TRUE);
cready_loop:
	c = bufread();
	switch (c) {
	case -1:
		if(errno == EINTR || errno == EPIPE)goto cready_loop;
		syserr("read");
	case 0:
		cbuf = (char)EMPTY;
		return(FALSE);
	default:
		cbuf = (char)c;
		return(TRUE);
	}
}


int cget()
{
	int  c;
	char c1;
	c = (int) cbuf;
	if (c != EMPTY) {
		c=(int)cbuf;
		cbuf=(char)EMPTY;
		return(c & 0377);
	}
cget_loop:
	c = bufread() ;
	switch(c) {
	case -1:
		if(errno == EINTR || errno == EPIPE)goto cget_loop;
		syserr("read");
	case 0:
		goto cget_loop;
	default:
		return(c & 0377);
	}
}
int cget_chat()
{
	int  c;
	char c1;
	c = (int) cbuf;
	if (c != EMPTY) {
		c=(int)cbuf;
		cbuf=(char)EMPTY;
		return(c & 0377);
	}
cget_loops:
	c = bufread();
	switch(c) {
	case -1:
		if(errno == EINTR || errno == EPIPE)return('\0');
		syserr("read");
	case 0:
		goto cget_loops;
	default:
		return(c & 0377);
	}
}


syserr(msg)
char *msg;
{
	extern int errno,sys_nerr;
	extern char *sys_errlist[];
	
	fprintf(stderr,"ERROR:%s (%d",msg,errno);
	if (errno>0 && errno < sys_nerr)
		fprintf(stderr,";%s)\n",sys_errlist[errno]);
	else
		fprintf(stderr,")\n");
	exit(1);
}
fatal(msg)
char *msg;
{
	fprintf(stderr,"ERROR:%s\n",msg);
	exit(1);
}

setraw()
{
	struct termio tbuf;
	if(ioctl(0,TCGETA,&tbuf) == -1)
		syserr("ioctl");
	tbufsave=tbuf;
	tbuf.c_iflag = (IXANY | IGNPAR | IXON | ISTRIP);
	tbuf.c_lflag = ISIG;
	tbuf.c_oflag = 0;
	tbuf.c_cc[VINTR] = 0x0b;    /* Control K */
	tbuf.c_cc[4] =1;
	tbuf.c_cc[5] =5;
	if(ioctl(0,TCSETA,&tbuf) == -1)
		syserr("ioctl2");
	if(ioctl(1,TCSETA,&tbuf) == -1)
		syserr("ioctl2");
}

restore()
{
	if (ioctl(0,TCSETAF,&tbufsave) == -1)
		syserr("ioctl3");
}

int bufread()
{
	static char sTdbuf[BUFSIZ+1];
	static char *bufp = sTdbuf;
	static int nb = 0;
	int n;
	if( nb == 0 )
		{
		n = read(0, sTdbuf, BUFSIZ);
		if ( n <= 0 ) return(n);
		nb = n;
		bufp = sTdbuf;
		}
	--nb;
	return(*bufp++);
}
