/*
 * Standalone console I/O
 */

char	consaddr	= 0x10;
char	conscmd2	= 0xee;

#define	DIS	0200
#define	ENA	0100
#define	DTR	0040
#define	WRT	0002
#define	CMD1	0001

#define PF		0100
#define FRERR		0040
#define	BSY		0010
#define EXA		0004
#define	CARR_OFF	0002

/*
 * Print a character on console.
 */
putchar(c)
register c;
{
	register timo;
	register waddr;

	waddr = consaddr | 01;
	/*
	 * Set baud rate & disarm interrupts
	 */
	oc(waddr, conscmd2);
	oc(waddr, DIS | ENA | WRT | DTR | CMD1);
	/*
	 *  If last char was a break or null, don't print
	*/
/*** ???
	if ((KLADDR->rbuf&0177) == 0)
		return;
***/
	timo = 30000;
	/*
	 * Try waiting for the console tty to come ready,
	 * otherwise give up after a reasonable time.
	 */
	while(ss(waddr)&BSY)
		if(--timo == 0)
			break;
	if(c == 0)
		return;
	wd(consaddr, c);
	if(c == '\n') {
		putchar('\r');
/***
		putchar(0177);
		putchar(0177);
***/
	}
	putchar(0);
}


getchar()
{
	register c, raddr;

	raddr = consaddr;
	/*
	 * Set baud rate & disarm interrupts
	 */
	oc(raddr, conscmd2);
	oc(raddr, DIS | ENA |  DTR | CMD1);
	/*
	 * Read a character
	 */
	c = rd(raddr);
	while (ss(raddr)&BSY)
		;
	c = rd(raddr)&0177;
	if (c=='\r')
		c = '\n';
	putchar(c);
	return(c);
}

gets(buf)
char	*buf;
{
register char *lp;
register c;

	lp = buf;
	for (;;) {
		c = getchar() & 0177;
		if (c>='A' && c<='Z')
			c -= 'A' - 'a';
		if (lp != buf && *(lp-1) == '\\') {
			lp--;
			if (c>='a' && c<='z') {
				c += 'A' - 'a';
				goto store;
			}
			switch ( c) {
			case '(':
				c = '{';
				break;
			case ')':
				c = '}';
				break;
			case '!':
				c = '|';
				break;
			case '^':
				c = '~';
				break;
			case '\'':
				c = '`';
				break;
			}
		}
	store:
		switch(c) {
		case '\n':
		case '\r':
			c = '\n';
			*lp++ = '\0';
			return;
		case '\b':
		case '#':
			lp--;
			if (lp < buf)
				lp = buf;
			continue;
		case '@':
			lp = buf;
			putchar('\n');
			continue;
		default:
			*lp++ = c;
		}
	}
}
