#ifndef lint
static char *RCSid = "$Header: pr.c,v 1.12 90/04/13 12:30:03 mr-frog Exp $";
#endif

/*
 * pr.c
 *
 * The pr routine historically arranged for nonbuffered i/o
 * because stdio didn't used to automatically flush stdout before
 * it read something from stdin.  Now pr() prepends an "output id"
 * in front of each line of text, informing the user interface
 * what sort of item it is seeing; prompt, noecho prompt,
 * more input data, etc.
 *
 * Dave Pare, 1986, 1989
 */

#include <ctype.h>
#include <varargs.h>
#include "proto.h"
#include "misc.h"
#include "nat.h"
#include "io.h"

static	int bol = 1;
extern	iop_t playerio;

pr(buf)
	char *buf;
{
	pr_id(C_DATA, buf);
}

pr_id(id, buf)
	int	id;
	char	*buf;
{
	register char *p;
	register char *bp;
	register int len;

	bp = buf;
	while (*bp != '\0') {
		if (bol) {
			outid(id);
			bol = 0;
		}
		p = index(bp, '\n');
		if (p != 0) {
			len = (p - bp) + 1;
			io_write(playerio, bp, len);
			bp += len;
			bol++;
		} else {
			len = io_puts(playerio, bp);
			bp += len;
		}
	}
}

/*
 * highlighted characters have hex 80 or'ed in
 * with them to designate their highlightedness
 */
pr_hilite(buf)
	char *buf;
{
	register char *bp;
	register char c;
	char	*p;

	p = malloc(strlen(buf) + 1);
	strcpy(p, buf);
	for (bp=p; c = *bp; bp++)
		if (isprint(c))
			*bp |= 0x80;
	pr(p);
	free(p);
}

/*
 * output hex code + space
 */
outid(n)
	int	n;
{
	char	c;
	char	buf[2];

	if (n > 16) {
		logerror("outid: %d not valid code\n", n);
		return;
	}
	if (n >= 10)
		c = 'a' - 10 + n;
	else
		c = '0' + n;
	buf[0] = c;
	buf[1] = ' ';
	io_write(playerio, buf, sizeof(buf));
}

prredir(redir)
	char	*redir;
{
	if (*redir == '>')
		outid(C_REDIR);
	else
		outid(C_PIPE);
	io_write(playerio, redir, strlen(redir));
	io_write(playerio, "\n", 1);
}

prexec(file)
	char	*file;
{
	outid(C_EXECUTE);
	io_write(playerio, file, strlen(file));
	io_write(playerio, "\n", 1);
}

/*
 * informs user interface that it should immediately
 * flush it's stdout after receiving this line.  This
 * is probably a prompt.
 */
prflush(buf)
	char	*buf;
{
	if (!bol) {
		io_write(playerio, "\n", 1);
		bol = 1;
	}
	pr_id(C_FLUSH, buf);
	io_write(playerio, "\n", 1);
	bol = 1;
}

prprompt(min, btu)
	int	min;
	int	btu;
{
	char	buf[32];

	outid(C_PROMPT);
	sprintf(buf, "%d %d\n", min, btu);
	io_write(playerio, buf, strlen(buf));
}

showvers(vers)
	int	vers;
{
	char	buf[10];

	(void) outid(C_INIT);
	sprintf(buf, "%d\n", vers);
	io_puts(playerio, buf);
}

int
prmptrd(prompt, str, size)
	char	*prompt;
	char	*str;
	int	size;
{
	int	r;

	prflush(prompt);
	if ((r = recvclient(str, size)) < 0)
		return r;
	if (*str == 0)
		return 1;
	return strlen(str);
}

prdate()
{
	extern	char *ctime();
	long	now;

	(void) time(&now);
	pr(ctime(&now));
}
