/* This is the new stuff.  */

/* The routines in lterm.asm handle the function keys.  If a function key
   is read, the high order bit is set high.  */

#include "mince.gbl"

MDebug()
{

	tlrow = -1;		     /* forget any saved row */
	TSetPoint(0, 0);
	TCLEOL();
	BSetMod(BScrnMrk(tmp));
	TPrntStr("npages: ");
	ltot((long) npages);
	TSetPoint(1, 0);
	TCLEOL();
	BSetMod(BScrnMrk(tmp));
	TForce();
	KbWait();
	if (tmp>=divide) ModeLine();
}

/*
MDebug()
{
	char *bptr;

	tmp= -1;
	tlrow = -1;		     /* forget any saved row */
	bptr = buffs[cbuff].bmodes;
	for (cnt=MAXMODES-1; cnt>=0; --cnt){
		TSetPoint(++tmp,0);
		TCLEOL();
		BSetMod(BScrnMrk(tmp));
		TPrntStr("*(bptr + ");
		TPrntStr(") ");
		ltot((long) cnt);
		TPrntStr(" : ");
		TPrntChar(*(bptr + cnt));
		}
	TSetPoint(++tmp,0);
	TCLEOL();
	BSetMod(BScrnMrk(tmp));
	TPrntStr("mode = ");
	TPrntStr(mode);
	TSetPoint(++tmp,0);
	TCLEOL();
	BSetMod(BScrnMrk(tmp));
	TForce();
	KbWait();
	if (tmp>=divide) ModeLine();
}
*/

MNewDsp()			/* move down arg lines and redisplay*/
{						/* Perfect Writer */
	Disp(FORWARD);
	}

Disp(dir)
int dir;
{
	if (argp){
		if (!VMovCmnd(lfunct)) lcol=BGetCol();
		while(arg-- > 0) dir ? NLSrch() : RNLSrch();
		BMakeCol(lcol);
		}
	arg=0;
	NewDsp();
	}

MRNewDsp()			/* move arg lines previous and redisplay */
{						/* Perfect Writer */
	Disp(BACKWARD);
	}

MToglC()	/* (C-^)  Toggle the case of a  character */
{						/* Perfect Writer */
	tmp = Buff();
	if (tmp >= 'a' && tmp <= 'z') tmp = tmp - 040;
	else if ( tmp >= 'A' && tmp <= 'Z') tmp = tmp + 040;
	if ( tmp != Buff()){
		BDelete(1);
		BInsert(tmp);
	} else BMove(1);
}

MDropLine()		/* drop rest of this line vertically */
{						/* Perfect Writer */
	if (BIsEnd() || IsNL()){
		BInsert(NL);
		BMove(-1);
		return;
		}
	TKbChk();
	tmp=BGetCol();
	BInsert(NL);
	TIndent(tmp);
	RNLSrch();
}

MCloseWhite()		/* replace surrounding greyspace with a blank */
{						/* Perfect Writer */
	do BMove(-1);
	while(!BIsStart() && IsGray());
	BMove(1);
	MDelWhite();
	while (!BIsEnd() && IsNL()){
		BDelete(1);
		MDelWhite();
		TKbChk();
		}
	Binsert(' ');
	arg=0;
}

/* if you want M-<digit> to work for arguments, put this on M-0 through
M-9, ... */
MArgDgt()				/* meta-digit arguments */
{						/* Perfect Writer */
	arg=(cmnd&0x7f)-'0';
	NumArg(arg);
	}

/* ... and put this on C-U. */
MArg()				/* set up arguments */
{						/* Perfect Writer */
	arg *= 4;
	NumArg(0);
	}

/* internal to the above. */
NumArg(tmp)			/* collect numeric arguments */
	int tmp;
{						/* Perfect Writer */
	int tchar, eflag, cflag;

	cflag = FALSE;
	eflag = ArgEcho(arg);
	while ((tchar=(cmnd=TGetKb())&0x7F)>='0' && tchar<='9') {
		tmp=tmp*10+tchar-'0';
		cflag=TRUE;
		eflag |= ArgEcho(tmp);
		}
	if (cflag) arg=tmp;
	if (eflag) ClrEcho();
	argp=TRUE;
	MapFuncKey();
	(*functs[cmnd])();	/* execute selected function */
	lfunct=functs[cmnd];
	TKbChk();
	}

MInsSFile()						/* Perfect Writer */
{
	char tname[FILMAX];

	arg=0;
	strcpy(tname,buffs[cbuff].fname);	/* prep for this file return */
	if (!GetArg("File To Insert<CR>: ",CR,tname,FILMAX))
		return;
	dfltext(tname, MSS);
	if (!OkFile(tname)) return;
	BMrkToPnt(mark);
	BSwitchTo(del_buff);
	TKbChk();
	if (!BReadFile(tname)) {
		Error("Not Found");
		BSwitchTo(buffs[cbuff].bbuff);
		return;
		}
	tmark=BCreMrk();
	BMrkToPnt(tmark);
	TKbChk();
	BToEnd();
	BCopyRgn(tmark,buffs[cbuff].bbuff);
	BKillMrk(tmark);
	BSwitchTo(buffs[cbuff].bbuff);
	TKbChk();
	ClrEcho();
	}

MWrtRgn()		/* Writes the region to the specified filename */
{						/* Perfect Writer */
	char tname[FILMAX];

	arg=0;
	strcpy(tname,buffs[cbuff].fname);	/* prep for this file return */
	if (!GetArg("Write Region To File<CR>: ",CR,tname,FILMAX))
		return;
	dfltext(tname, MSS);
	if (!OkFile(tname)) return;
	CleanBuff(del_buff);
	TKbChk();
	BCopyRgn(mark,del_buff);		/* Copy the region to the del_buff */
	BSwitchTo(del_buff);		/* prepare to write */
	Echo("Writing...");
	TKbChk();
	if(!BWriteFile(tname)) Error("Can't write to file");
	echo("Region written to file");
	BSwitchTo(buffs[cbuff].bbuff);	/* get back to original buffer */
	}

CleanBuff(buff)		/* This empties the buff */
int buff;
{
	int ltmark;

	BSwitchTo(buff);
	BToEnd();
	ltmark=BCreMrk();
	BToStart();
	BDelToMrk(ltmark);
	BKillMrk(ltmark);
	BSwitchTo(buffs[cbuff].bbuff);
	}

OkFile(fname)
char *fname;
{
	int i;

	i=0;
	UpCase(fname);
	while (fname[i]) {
		if ( !(isdigit(fname[i]) || isalpha(fname[i]))
			&& (fname[i] != '$')  && (fname[i] != '&') && (fname[i] != '#')
			&& (fname[i] != '@')  && (fname[i] != '!') && (fname[i] != '%')
			&& (fname[i] != '\`') && (fname[i] != '(') && (fname[i] != ')')
			&& (fname[i] != '-')  && (fname[i] != '<') && (fname[i] != '>')
			&& (fname[i] != '{')  && (fname[i] != '}') && (fname[i] != '_')
			&& (fname[i] != '\\') && (fname[i] != '^') && (fname[i] != '~')
			&& (fname[i] != '\'') && (fname[i] != '|') && (fname[i] != '.')
			&& (fname[i] != ':'))
			{
			echo("Illegal File Name: ");
			TPrntStr(fname);
			return(FALSE);
			}
		i++;
		}
	return(TRUE);
	}

MIndNL()			/* Indent new line same as current */
{						/* Perfect Writer */
	ToEndLine();
	MIndRest();
	}

/* This splits the line and indents */
MIndRest()			/* move rest of line to indented new line */
{						/* Perfect Writer */
	tmark=BCreMrk();
	cnt = GetInd();
	BPntToMrk(tmark);
	TKbChk();
	Binsert (NL);
	SIndent (cnt);
	BKillMrk(tmark);
	}

GetInd()				/* Get this line's indentation */
{						/* Perfect Writer */
	int IsWhite();

	ToBegLine();
	MovePast(&IsWhite,FORWARD);
	return (BGetCol());
	}

MHelp()
{

	FILE *fp;
	int nlines;
	char numbuf[3];

	if((fp = fopen("pw.hlp", "r")) == NULL)
		if((fp = fopen("a:pw.hlp", "r")) == NULL){
			Error("Can't open help file");
			return;
		}
	if(!help_page){
		nlines = DispHPage(fp);
		*numbuf = NULL;
		do 
			if (!GetArg("Help Selection <CR>: ",CR,numbuf,3)){
			goto out;
			}
		while (*numbuf==NULL);
		stcd_i(numbuf, &help_page);
		if(help_page > 0 && help_page <= 16){
			HelpSkip(fp, 4);			/* skip past function key help */
			HelpSkip(fp, help_page);
		}
		else{
			Error("Invalid Selection");
			goto out;
		}
	}
	else
		HelpSkip(fp, help_page);
	nlines = DispHPage(fp);
	TForce();
	KbWait();
out:
	if (nlines>=divide)
		ModeLine();
	fclose(fp);
	help_page = 0;
}

HelpSkip(fp, n)
FILE *fp;
int n;
{

	char hbuf[80];

	while(n){
		do
			fgets(hbuf, 79, fp);
		while(*hbuf != '=');
		n--;
	}
}

DispHPage(fp)
FILE *fp;
{

	char hbuf[80];
	register int tmp, i;

	tlrow = -1;		     /* forget any saved row */
	
	for(tmp = 0; tmp < 8; tmp++){
		fgets(hbuf, 79, fp);
		hbuf[strlen(hbuf) - 1] = NULL;
		DispInfo(tmp, 0, hbuf);
	}

	DispInfo(tmp, 0, 0);
	for(i = 0; i < TMaxCol()-1; i++)
		TPrntChar(205);
	return tmp;
}

DispInfo(row, col, string)
int row, col;
char *string;
{

	TSetPoint(row, col);
	TCLEOL();
	BSetMod(BScrnMrk(row));
	if(string)
		TPrntStr(string);
}
	
MOpenIndLin()			/* open line at current indentation */
{
	int	tmp;

	tmp = GetInd();
	ToBegLine();
	BInsert (NL);
	BMove(-1);
	TIndent (tmp);
}

MIndntRgn()			/* indent the region */
{
	IndRgn (indentcol);
}

MUndntRgn()			/* undent the region */
{
	IndRgn (-indentcol);
}

/*
**	Internal to the above, ``MIndntRgn()'' and ``MUndntRgn()''
*/
IndRgn(amt)			/* add amt to the region's indentation */
{
	int	tmp;

	if (tmp = BIsAfterMrk (mark)) BSwapPnt (mark);
	tmark = BCreMrk();
	while (BIsBeforeMrk (mark)) {
		cnt = GetInd();
		MDelWhite();
		TIndent (cnt + amt);
		NLSrch();
	}
	TKbChk();
	BPntToMrk (tmark);
	if (tmp) BSwapPnt (mark);
	BKillMrk (tmark);
}

#define	PS	"ps"
#define	PS1	"a:ps"

MGoSpell()
{
	char name[FILMAX];
	char command[STRMAX];

	arg=0;
	*name=NULL;
	strcpy(name,buffs[cbuff].fname);	/* prep for this file return */
	if (!GetArg("File To Spell <CR>: ",CR,name,FILMAX)) return;
	if (!OkFile(name)) return;

 	if ( !strcmp(name,buffs[cbuff].fname) && BModp(buffs[cbuff].bbuff)
		&& !BWriteFile(name) ){ 		/* if the buffer and file to spell */
		Error("Can't Save Buffer");	/* match, and it is modified */
		return;					/* try writing it out */
		}						/* else error out */
	UpCase(name);
	if(AnyModified()) return; /* quit if any modified buffers we still want */
	TClrWind();
	strcpy(command, "-n ");
	strcat(command, name);
	exec(PS, command);		/* call the speller */
	exec(PS1, command);		/* everywhere */

	NewDsp();					/* recover from TFini() */
	Error("Cannot find PS");
	}

MFKeyHelp()
{
	help_page = 1;
	MHelp();
}

MSFKeyHelp()
{
	help_page = 2;
	MHelp();
}

MCFKeyHelp()
{
	help_page = 3;
	MHelp();
}

MAFKeyHelp()
{
	help_page = 4;
	MHelp();
}


MPageBreaks()
{
	long line;
	int lineincr;
	char ibuf[5];

	line = arg = 0;			/* set up */
	*ibuf = NULL;
	if (!GetArg("Number of lines per page <50>: ",CR,ibuf,5))
		return;
	if(*ibuf)
		stcd_i(ibuf, &lineincr);
	else
		lineincr = 50;
	tmark=BCreMrk();			/* this is where we are */
	BToStart();				/* to the beginning */
	while(!BIsEnd()){			/* not at the end */
		NLSrch();				/* look for NL */
		if(++line % lineincr == 0)
			BInsStr("@newpage\n");
		}
	PtMkKill(tmark);			/* all done with that mark */
}

BInsStr(string)
char *string;
{
	while(*string)
		BInsert(*string++);
}

#define PF	"pf"
#define PF1	"a:pf"

MPrint()
{
	char name[FILMAX];
	char command[STRMAX];
	char tabbuf[5];
	char yes[4];

	arg=0;
	*name=NULL;
	*yes = NULL;
	strcpy(name,buffs[cbuff].fname);	/* prep for this file return */
/*
	if (!GetArg("Continuous paper? <Yes>: ",CR,yes,4)) return;
*/
	if (!OkFile(name)) return;

 	if ( !strcmp(name,buffs[cbuff].fname) && BModp(buffs[cbuff].bbuff)
		&& !BWriteFile(name) ){ 		/* if the buffer and file to spell */
		Error("Can't Save Buffer");	/* match, and it is modified */
		return;					/* try writing it out */
		}						/* else error out */
	UpCase(name);
	if(AnyModified()) return; /* quit if any modified buffers we still want */
	TClrWind();
	strcpy(command, "-typewriter ");
	if(Ask("Pause for insertion of single sheets?"))
		strcat(command, "-pause ");
/*
	switch(*yes){
		case NULL:
		case 'y':
		case 'Y':
			break;
		default:
			strcat(command, "-pause ");
	}
*/
	strcat(command, "-p ");
	strcat(command, "-tab ");
	stci_d(tabbuf, tabincr, sizeof(tabbuf));
	strcat(command, tabbuf);
	strcat(command, " ");
	strcat(command, name);
	exec(PF, command);		/* call the speller */
	exec(PF1, command);		/* everywhere */
	NewDsp();					/* recover from TFini() */
	Error("Cannot find PF");
	}

/*
**	if the string pointed to by ``fn'' has no extension, 
**	dfltext appends the string pointed to by ``ext'' onto ``fn''.
**	Note:
**	dfltext assumes that enough space has been allocated in ``fn''
**	to handle the appending of ``ext''.
*/
dfltext(fn, ext)			/* default fn's extension to ext */
char *fn, *ext;
{
	while(*fn) if(*fn++ == '.') return;
	*fn++ = '.';
	strcpy(fn, ext);
}
