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

/* Given a filename, pick out one parargraph and type it. Paragraphs 
are assumed to be delimited by a CR LF CR LF sequence. Return 0 if no quote 
found. The file position between invokations is stored in FIDO.SYS. */

void quote(file)
char *file;	/* pointer to complete filename */
{
int f,i;
char mark[SS];
char c,reseek;

	f= opentf(file,0);			/* open it, */
	if (f == -1) return;			/* doesnt exist, */

	strcpy(mark,"XXXX");			/* must be anything but CR LF CR LF */
	reseek= 0;
	mcrlf();

/* Find the CR/LF/CR/LF preceeding this quote. This !KLUDGE! handles the
case where we switched quote files (due to language change). The only 
alternative I can think of is to keep a quote_pos for each language ... */

	lseek(f,fido.quote_pos,0);		/* seek to current position */
	if (fido.quote_pos > 8L) lseek(f,-5L,1); /* maybe backup a bit */

	do i= read(f,&c,1);
	while (i && !shiftin(c,mark));		/* find the CR/LF/CR/LF */

	while (1) {
		if (! read(f,&c,1)) {		/* "read error" */
			if (reseek++) break;	/*   if already reseeked, stop */
			lseek(f,(fido.quote_pos= 0L),0); /*   else reseek, */
			continue;		/* try again */
		}
		++fido.quote_pos;		/* current quote file position */
		if (shiftin(c,mark)) break;	/* found CR/LF/CR/LF */
		mconout(c);			/* output the character */
	}
	close(f);
	mcrlf();
}

/* Shift a character into the recognizer, return true if we've just
read a CR/LF/CR/LF */

static shiftin(c,mark)
char c,mark[];
{
int i;

	for (i= 0; i < 4; i++)			/* ASCII shift register */
		mark[i]= mark[i + 1];		/* slide 'em through */
	mark[3]= c;				/* add to the end */
	return(strcmp(mark,"\r\n\r\n") == 0);	/* test it */
}
