#include <stdio.h>
#include <time.h>
#include <memory.h>
#include <errno.h>
#include <libp.h>

extern FILE *_pstreams[_NFILE_];
extern char *_filenames[_NFILE_];
extern int maxfiles;

/* so if they use a larger buf size in ascii mode, we are ignoring
 * it in terms of DPMI calls which may not be a good thing...
 */
#define LBSIZE 511

static char localbuf[LBSIZE];
static int oneflush(FILE *stream)
{
	int rv = 0, lvl;
	if (stream->token == FILTOK) {
		if (stream->buffer)
			if (stream->flags & _F_OUT) {
				if (!(stream->flags & _F_BIN)) {
					int i;
					char *p = localbuf, *q = (char *) stream->buffer;
					for (i=-stream->bsize; i< stream->level; i++) {
						if (p >= localbuf + LBSIZE-1) {
							rv = _ll_write(stream->fd,localbuf,p-localbuf);
							if (rv < 0)
								break;
							p = localbuf;
						}
						if ((*p++ = *q++) == '\n') {
							*(p-1) = '\r';
							*p++ = '\n';
						}
					}
					if (p != localbuf && rv >=0 ) {
						rv = _ll_write(stream->fd,localbuf,p-localbuf);
					}
				}
				else {
					rv = _ll_write(stream->fd,stream->buffer,stream->bsize + stream->level);
				}
				if (rv < 0) {
					stream->flags |= _F_ERR;
					errno = ENOSPC;
					rv = EOF;
				}
				else rv = 0;
				stream->level = 0;
			}
			else if (stream->flags & _F_READ) {
				if (stream->level > 0) {
					rv = _ll_seek(stream->fd,-stream->level+1,SEEK_CUR);
					if (rv < 0) {
						stream->flags |= _F_ERR;
						errno = ENOSPC;
						rv = EOF;
					}
				}
				else rv = 0;
				memset(stream->buffer,0,stream->bsize);
				stream->level = 0;
			}
		stream->hold = 0;
		stream->curp = stream->buffer;
		stream->flags &= ~(_F_IN | _F_OUT);
		return rv;			
	}
	else {
		errno = _dos_errno = ENOENT;
		return EOF;
	}
}
int fflush(FILE *stream)
{
	int rv;
	if (stream)
		return(oneflush(stream));
	else {
		int i;
		for (i=0; i < maxfiles; i++)
			rv |= oneflush(_pstreams[i]);
	}
	return rv;
}