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

/****************************************************************************
 *
 * Function:    _stbuf
 *
 * Description: Complete any pending buffering for the stdout/stderr files.
 *
 * Input:       stream   - A pointer to the file to be initialized.
 *
 * Result:      TRUE to indicate the file is buffered, FALSE otherwise.
 */

int _stbuf (FILE *stream)
    {
    unsigned char *buff;
    FILE2    *stream2 = file2p (stream);
    FUNC_ENTRY ("_stbuf");
/*
 *  Attempt to find the buffer for this file.
 */
    if (stream == stdout)
        {
	buff = _bufout;
	_cflush++;
	_libc__cleanup = _cleanup;
        }
    else
        {
	if (stream == stderr)
	    {
	    buff = _buferr;
	    }
	else
	    {
	    buff = NULL;
	    }
        }
/*
 *  If the file is currently buffered then reject the operation.
 */
    if (anybuf (stream))
        {
	buff = NULL;
	}
/*
 *  Initialize the buffer pointers
 */
    if (buff != NULL)
        {
	stream->_ptr     =
        stream->_base    = buff;
	stream->_cnt     =
        stream2->_bufsiz = BUFSIZ;
	stream2->_flag2  = _IOYOURBUF;
	stream->_flag   |= _IOWRT;
/*
 *  Indicate a pending flush is required
 */
	_cflush++;
	_libc__cleanup = _cleanup;
        }
/*
 *  Return the status to the caller. If the buffer is non-null then the
 *  operation was completed.
 */
    FUNC_EXIT ("_stbuf");
    return (buff != NULL);
    }

/**************************************************************************
 *
 * Function:    _ftbuf
 *
 * Description:
 *    flush and dismantle the buffer for the file.
 *
 * Entry:
 *    flag     - TRUE if discard temp buffering on the stream
 *    stream   - The stream to process
 *
 * Result:
 *     none.
 */

void _ftbuf (int flag, FILE *stream)
    {
    FILE2 *stream2 = file2p (stream);
    FUNC_ENTRY ("_ftbuf");
/*
 *  If the file is to be flushed then flush the buffer and discard the
 *  temporary buffering.
 */
    if (stream2->_ttyflag != _IONOTTY && 
	(stream2->_ttyflag == _IOISTTY || isatty (fileno (stream))))
        {
	stream2->_ttyflag = _IOISTTY;
	if (flag)
	    {
	    if (stream == stdout || stream == stderr)
	        {
		fflush(stream);
		stream2->_flag2  = 0;
		stream2->_bufsiz = 0;
		stream->_base    =
		stream->_ptr     = NULL;
	        }
	  }
/*
 *  If the output buffer is local for stdout or stderr then flush the
 *  stream.
 */
	else
            {
	    if (stream->_base == _bufout || stream->_base == _buferr)
	        {
                fflush (stream);
	        }
	    }
      }
    else
      stream2->_ttyflag = _IONOTTY;
    FUNC_EXIT ("_ftbuf");
    }

