#include "fido.h"
#include <ascii.h>
#include "fidomem.h"
#include "proto.h"


/* See if the sysop's available, if so, beep and get his attention. Sysop must
type the right special character to acknowledge. */

void chat() {
int i;
char c;

	if (til_sched('Y',0,0) < 0) {		/* if no Yell sched now, */
		if (! dispbbs("page.bbs")) mprintf(CM+126);
		return;
	}
	if (test) {
		mprintf(CM+127);		/* "no sense paging yourself!" */
		return;
	}
	mprintf(CM+128,caller.name);		/* tell caller */
	cprintf(SM+29,caller.name,caller.times,minutes); /* tell sysop */

	for (i= 10; i; i--) {
		bdos(6,'\07');		/* local console */
		mconout('\07');
		delay(100);
		if (c= keyhit()) {
			c= tolower(c);
			if ((c == '1') || (c == 'c')) {
				talk();
				break;

			} else if (c == ' ') {
				i= 0;
				break;
			}
		}
	}
	if (i == 0) {
		mprintf(CM+129);				/* not available */
		lprintf(LM+29);
	}
}

/* Talk back and forth. Exit when sysop types ^Z. */

static talk() {

char c;
int i,insave,outsave;

	outsave= localout;
	insave= localin;
	localin= localout= 1;

	mprintf(CM+130);			/* "type to/from sysop" */
	cprintf(SM+110);			/* "sysop: Control-Z to stop" */
	yack();					/* talk */
	line= 0;
	mprintf(CM+131);			/* "done typing to sysop" */

	localin= insave;
	localout= outsave;
}

/* Get letters, make words, wrap them at the right places, and stop
when control-Z is entered. */

static yack() {

int width;
char word[SS];
int pc;
char c;

	width= uval(CLR_WID,CLR_WIDS) - 4;

	while (localin) {
		pc= 0;
		word[pc]= NUL;

		while (strlen(word) + column < width) {
			if (! localin) break;
			if (mconstat()) {
				c= mconin() & 0x7f;		/* get one word */
				if (c == CR) break;		/* stop if CR, */
				if (c == '\t') c= ' ';		/* make tabs usable */

				if ((c == BS) || (c == DEL)) {
					if (pc > 0) {		/* backspace first */
						erase(1);	/* deletes chars in */
						mconout(BS);	/* our word, */
						word[--pc]= NUL; 

					} else if (column > 0) {/* or if empty, */
						erase(1);	/* then in the line */
						mconout(BS);
					}

				} else if (c >= ' ') {		/* if printable, */
					mconout(c);
					word[pc++]= c;		/* else store until */
					word[pc]= NUL;		/* end of word or */
				}
				if ((c == ' ') || (c == ',')) break; /* too long */
			}

		}
		if (c == CR) {
			mcrlf();
		}
		if (strlen(word) + column >= width) {	/* doesnt fit */
			erase(strlen(word));		/* clear last word, */
			mprintf(0,"\r\n%s",word);	/* display on next line */
		}
		line= 0;				/* no "more" ! */
	}
}
