/* TTY input driver */
#include <stdio.h>

#include "global.h"

int ttymode;
#define TTY_COOKED	0
#define	TTY_RAW	1

int ttyecho;
#define	TTY_NOECHO	0
#define	TTY_ECHO	1

#define	LINESIZE	256

#define	CTLU	21
#define CTLR	18

raw()
{
	ttymode = TTY_RAW;
}

cooked()
{
	ttymode = TTY_COOKED;
}

/* Accept characters from the incoming tty buffer and process them
 * (if in cooked mode) or just pass them directly (if in raw mode).
 * Returns the number of characters available for use; if non-zero,
 * also stashes a pointer to the character(s) in the "buf" argument.
 */
 /*Control-R added by df for retype of lines - useful in Telnet */
 
void
echo()
{
	ttyecho = TTY_ECHO;
}

void
noecho()
{
	ttyecho = TTY_NOECHO;
}

int
ttydriv(c,buf)
char c;
char **buf;
{
	static char linebuf[LINESIZE];
	static char *cp = linebuf;
	char *rp ;
	int cnt;

	if(buf == (char **)NULL)
		return 0;	/* paranoia check */

	cnt = 0;
	switch(ttymode){
	case TTY_RAW:
		*cp++ = c;
		cnt = cp - linebuf;
		cp = linebuf;
		break;
	case TTY_COOKED:
		/* Perform cooked-mode line editing */
		switch(c & 0x7f){
		case '\r':	/* CR and LF are equivalent */
		case '\n':
			*cp++ = '\r';
			*cp++ = '\n';
			printf("\n");
			cnt = cp - linebuf;
			cp = linebuf;
			break;
		case '\b':		/* Backspace */
			if(cp != linebuf){
				cp--;
				if (ttyecho)
					printf("\b \b");
			}
			break;
		case CTLR:	/* print line buffer */
			if(ttyecho)
				printf("^R");
			printf("\n");
			if(ttyecho) {
				rp = linebuf ;
				while (rp < cp)
					putchar(*rp++) ;
			}
			break ;
		case CTLU:	/* Line kill */
			if(ttyecho) {
				while(cp != linebuf){
					cp--;
					printf("\b \b");
				}
			} else
				cp = linebuf;
			break;
		default:	/* Ordinary character */
			*cp++ = c;
#ifndef	AMIGA
			if (ttyecho)
				putchar(c);
#endif
			if(cp >= &linebuf[LINESIZE]){
				cnt = cp - linebuf;
				cp = linebuf;
			}
			break;
		}
	}
	if(cnt != 0)
		*buf = linebuf;
	else
		*buf = NULLCHAR;
	fflush(stdout);
	return cnt;
}
