#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;

static int oneflush(FILE *stream)
{
	int rv = 0;
	if (stream->token == FILTOK) {
		if (stream->buffer)
			if (stream->flags & _F_OUT) {
				rv = _ll_write(stream->fd,stream->buffer,stream->level);
				if (!rv) {
					stream->flags |= _F_ERR;
					rv = EOF;
				}
				else rv = 0;
				stream->level = 0;
			}
			else if (stream->flags & _F_READ) {
				memset(stream->buffer,0,stream->bsize);
				stream->level = 0;
			}
		stream->hold = 0;
		stream->curp = stream->buffer;
		if (_ll_seek(stream->fd,_ll_getpos(stream->fd)-stream->level,SEEK_SET))
			rv = EOF;
		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;
}