/* #define	TESTING	*/
/*
 *
 * Synopsis
 *
 *	int
 *	pending()
 *
 * Description
 *
 *	Returns the number of characters waiting at the terminal
 *	(zero if none) or -1 if an error occurs.  Nothing is read
 *
 *	Note -- this routine does not prevent CTRL/C or CTRL/Y aborts
 *	from occurring.
 *
 */

#include	<stdio.h>
#include	<ssdef>
#include	<iodef>
#include	<descrip>

#define	FALSE	0
#define	TRUE	1
#define	EOS	0

/*
 * Local static database:
 */

static $DESCRIPTOR(inpdev, "TT");	/* Terminal to use for input	*/

/*
 * Local variables
 */

static long	ichan;			/* Gets channel number for TT:	*/
static char	opened = FALSE;		/* TRUE when opened		*/

int
pending()
/*
 * Get one byte without echoing
 */
{
	register int	errorcode;
	struct IOSTAB {
		short int	status;
		short int	offset_to_terminator;
		short int	terminator;
		short int	terminator_size;
	} status;
	struct type_ahead {
	    short	pending_count;
	    char	first_character;
	    char	char_reserved;
	    int		long_reserved;
	} type_ahead;

	if (!opened) {
	    if ((errorcode = sys$assign(&inpdev, &ichan, 0, 0)) != SS$_NORMAL) {
		fprintf(stderr, "KBIN assign failed.  code = %X\n", errorcode);
		exit(errorcode);
	    }
            else opened = TRUE;
	}
	errorcode = sys$qiow(1,	/* Event flag 			*/
		ichan,		/* Input channel		*/
		IO$_SENSEMODE | IO$M_TYPEAHDCNT,
		&status,	/* I/O status block		*/
		NULL,		/* AST block (none)		*/
		0,		/* AST parameter		*/
		&type_ahead,	/* P1 - buffer			*/
		sizeof type_ahead, /* P2 - buffer length	*/
		0,		/* P3 - 			*/
		NULL,		/* P4 - 			*/
		NULL,		/* P5 - ignored (prompt buffer)	*/
		0);		/* P6 - ignored (prompt size)	*/
	return ((errorcode != SS$_NORMAL) ? -1 : type_ahead.pending_count);
}

#ifdef	TESTING
main() {
	register int	c;
	register int	count;

	for (;;) {
	    printf("Pending %d", (count = pending()));
	    while (--count >= 0) {
		c = kbin();
		putchar(c);
		if (c == 'Z' || c == ('Z' - 64))
		    break;
	    }
	    putchar('\n');
	    sleep(2);
	}
}
#endif

