#include <stdio.h>
#include "file2.h"
#include "internal.h"
#include <trace.h>

/***************************************************************************
 *
 * Function:     ungetc
 *
 * Description:
 *   Return a character to the input buffer.
 *
 * Entry:
 *   nChar     - Input character to be returned to the buffer
 *   stream    - Pointer to the input stream
 *
 * Returns:
 *   The input character or EOF to indicate an error condition.
 */

int ungetc (const int nChar, FILE *stream)
    {
    int  nAnswer = (int) nChar;
    FUNC_ENTRY ("ungetc");
/*
 *  If the stream is not open for read access then reject the request.
 */
    if (nAnswer != EOF && (stream->_flag & _IOREAD) == 0)
        {
	nAnswer = EOF;
        }
/*
 *  Allocate a buffer if one is not allocated
 */
    if (nAnswer != EOF)
        {
	nAnswer &= 0xFF;
	if (stream->_base == NULL)
	    {
	    _getbuf(stream);
	    }
/*
 *  If the file has a buffer then reject the request if there is no
 *  space to store the character.
 */
	if (stream->_ptr == stream->_base)
	    {
	    if (stream->_cnt != 0)
	        {
		nAnswer = EOF;
	        }
	    else
	        {
		++stream->_ptr;
	        }
	    }
/*
 *  Adjust the count, store the character, and reset the EOF indicator.
 */
	if (nAnswer != EOF)
	    {
	    ++stream->_cnt;
	    *--stream->_ptr = (unsigned char) nAnswer;
	    stream->_flag  &= ~_IOEOF;
/*
 *  Set the UNGETC flag.
 */
	    if ((stream->_flag & _IOSTRG) == 0)
	        {
		FILE2 *stream2 = file2p (stream);
		stream2->_flag2 |= _IOUNGETC;
	        }
	    }
        }
/*
 *  Return the character or EOF to the caller.
 */
    FUNC_EXIT ("ungetc");
    return (nAnswer);
    }
    
