/*
 * All of this obscenity is to support talking to a KB: device on RSTS/E
 * The DECUS C implementation is so dense it thinks that all KBnn: devices
 * are the user's console terminal, which isn't too helpful...
 */

#include	<rsts.h>
#include	<stdio.h>
/*
 * kb_open(name) - open file "name" via low-level RSTS I/O
 */
kb_open(name)
char		*name;			/* Device name			*/
{
	register int	i;		/* Channel search index		*/
	char		work[30];	/* Buffer for open		*/
	extern	int	$$ferr;		/* Error value			*/
	extern	int	$$rsts;		/* Are we really RSTS/E?	*/
	extern	char	*E$$NOD;	/* Not a device			*/
	extern	char	*E$$FAT;	/* Illegal function		*/
	extern	char	*E$$NOC;	/* No channels available	*/

	if (!$$rsts) {
	    $$ferr = 257;		/* If not on real RSTS/E	*/
	    goto error1;
	}

	for (i = 12; i > 0; i--) {	/* Look for an idle I/O channel	*/
	    clrxrb();
	    xrb.xrci = i * 2;
	    if (rstsys(_POSTN) == NOTOPN)
		break;
	}
	if (i <= 0) {			/* If couldn't find one		*/
	    $$ferr = (int) &E$$NOC;
	    goto error1;
	}
	sprintf(work, "%s/mo:%d", name, 1+16+32);
	if (($$ferr = rs_open(i, work, "r")) != 0) {
	    goto error1;		/* Try to open the file		*/
	}
	if ((firqb.fqflag & 0xFF) != TTYHND) {
	    $$ferr = (int) &E$$NOD;	/* Not a terminal device	*/
	    rs_close(i);
	    goto error1;
	}
	return (i);			/* Tell the user the channel #	*/

error1:	return (NULL);			/* General bail-out		*/
}

/*
 * kb_spit(chan, chr) - write character "chr" to channel "chan"
 */
kb_spit(chan, chr)
register int	chan, chr;		/* Channel, character		*/
{
	int		code;
	char		work[2];	/* Buffer for write		*/
	extern int	$$ferr;

	if (chr == 0x0A) {
	    work[0] = 0x0D;		/* Force LF to CR/LF		*/
	    if ((code = rs_write(chan, work, 1, 0, 0, 0)) != 0) {
		$$ferr = code;
		perror("KBnn:");
		exit(IO_ERROR);
	    }
	}
	work[0] = chr;
	if ((code = rs_write(chan, work, 1, 0, 0, 0)) != 0) {
	    $$ferr = code;
	    perror("KBnn:");
	    exit(IO_ERROR);
	}
}

/*
 * kb_close(chan) - close the device on channel "chan"
 */
kb_close(chan)
register int	chan;			/* Channel			*/
{
	rs_close(chan);			/* Errors? Who cares!		*/
}
                                                                                                                                                                                                                                                                                                                                                                                   