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

int _readbuf(FILE *stream)
{
	int sz,sz2;
	if (stream->buffer) {
		/* if a buffer, attempt to read the whole thing... */
		stream->curp = stream->buffer;
		sz2 = stream->bsize;
	}
	else {
		/* if no buffer, we blit one byte into stream->hold */
		stream->curp = &stream->hold;
		sz2 = 1;
	}
	stream->level = sz = _ll_read(stream->fd,stream->curp,sz2);
	/* get out on error */
	if (sz < 0) {
		stream->flags |= _F_ERR;
		errno = EIO;
		return EOF;
	}
	/* get out on EOF */
	else if (sz == 0) {
		stream->flags |= _F_EOF;
		return EOF;
	}
	else {
		if (!(stream->flags & _F_BIN)) {
			/* handle ASCIIizing the stuff */
			unsigned char *p = stream->buffer,*q=p;
			int len = stream->level;
			int i;
			for (i=0; i < len; i++)
				if (*p == 0x1a) {
					break;
				}
				else {
					if (*p == '\r') {
						p++;
					}
					else
						*q++ = *p++;
				}
			stream->level = q - stream->buffer;
		}
	}
	return 0;
}
int fgetc(FILE *stream)
{
	int rv;
	if (stream->token != FILTOK) {
		errno = _dos_errno = ENOENT;
		return EOF;
	}
	if (!(stream->flags & _F_READ)) {
		stream->flags |= _F_ERR;
		errno = EFAULT;
		return EOF;
	}
	if (stream == stdin)
		fflush(stdout);
	if (!stream->flags & _F_IN) {
		if (stream->flags & _F_OUT) {
			if (fflush(stream))
				return EOF;
		}
		stream->flags &= ~_F_OUT;
		stream->flags |= _F_IN;
		stream->level = 0;
	}
	if (stream->flags & _F_EOF)
		return EOF;
	if (stream->hold) {
		rv = stream->hold;
		stream->hold = 0;
		return rv;
	}
	if (--stream->level <= 0) {
		rv = _readbuf(stream);
		if (rv)
			return rv;
	}
	return (unsigned char *)(*stream->curp++);
}
int _fgetc(FILE *stream)
{
	stream->level++;
	return fgetc(stream);
}
#undef getc
#undef getchar
int getc(FILE *stream)
{
	return getc(stream);
}
int getchar(void)
{
	return getc(stdin);
}
		