#include "../sccshead/sfile.h"

char getl____[] "~|^`getl.c:	2.7";

/*
	Routine to open a file for input.
*/

opnl(buf,file,fd)
struct Ibufr *buf;
char file[];
int fd;
{
	if(nargs() == 3) buf->Ifildes = fd;
	else buf->Ifildes = xopen(file,0);

	buf->Irecptr = buf->Ibuff2;
	buf->Iend = buf->Irecptr + 511;
	buf->Ilen = 512;

	return(0);
}


/*
	Routine to read a line from a "normal" ASCII file; that is,
	a file in which lines are terminated with newlines.  Returns
	1 on a read error; otherwise returns address of the line.
	Address is also in buf->Irecptr.  Length (including newline)
	is in buf->Ilen.
*/

getl(buf)
struct Ibufr *buf;
{
	register char *p, *q;
	register int n;
	int i, r;

	p = buf->Irecptr =+ buf->Ilen;

	i = 0;
	while(1) {
		while(p <= buf->Iend)
			if(*p++ == '\n') {
				buf->Ilen = p - buf->Irecptr;
				return(buf->Irecptr);
			}

		if(i++ == 1) return(1);

		q = buf->Irecptr;
		p = buf->Irecptr =- buf->Iend-buf->Ibuff2+1;

		while(q <= buf->Iend) *p++ = *q++;

		buf->Iend = buf->Ibuff2 - 1;
		do {
			r = 512 - (buf->Iend - buf->Ibuff2 + 1);
			n = read(buf->Ifildes,buf->Iend+1,r);
			buf->Iend =+ n;
		} while(n > 0 && n != r && *buf->Iend != '\n');
		if(buf->Iend < buf->Ibuff2) return(1);
	}
}
