#include <stdio.h>
#include <errno.h>
#include <string.h>

#undef ungetc
int ungetc(int c, FILE *stream)
{
	if (stream->token != FILTOK) {
		errno = _dos_errno = ENOENT;
		return EOF;
	}
	if (stream->buffer) {
		if ((stream->flags & _F_IN) && stream->curp != stream->buffer) {
			if (stream->level == stream->bsize) {
				errno = _dos_errno = ENOSPC;
				return EOF;
			}
			if (stream->curp == stream->buffer) {
				int len;
				memmove (stream->buffer + (len = stream->bsize - stream->level), 
						stream->buffer, stream->level);
				stream->curp += len;
			}
		}
		else {
			if (fflush(stream))
				return EOF;
			stream->flags |= _F_IN;
	    stream->level = 0;
			stream->curp = stream->buffer+stream->bsize;
		}
		stream->level++;
		*--stream->curp = (char)c;
	}
	else {
		if (stream->hold) {
			errno = _dos_errno = ENOSPC;
			return EOF;
		}
		stream->hold = (char)c;
	}
	return c;
}
int _ungetc(int c, FILE *stream)
{
	return ungetc(c, stream);
}