/*
 * |-----------------------------------------------------------|
 * | Copyright (c) 1991, 1990 MIPS Computer Systems, Inc.      |
 * | All Rights Reserved                                       |
 * |-----------------------------------------------------------|
 * |          Restricted Rights Legend                         |
 * | Use, duplication, or disclosure by the Government is      |
 * | subject to restrictions as set forth in                   |
 * | subparagraph (c)(1)(ii) of the Rights in Technical        |
 * | Data and Computer Software Clause of DFARS 252.227-7013.  |
 * |         MIPS Computer Systems, Inc.                       |
 * |         950 DeGuigne Avenue                               |
 * |         Sunnyvale, California 94088-3650, USA             |
 * |-----------------------------------------------------------|
 */
#ident	"$Header: setbuf.c,v 1.10.2.1 92/06/24 14:01:43 marker Exp $"

/*	Copyright (c) 1984 AT&T	*/
/*	  All Rights Reserved  	*/

/*	THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T	*/
/*	The copyright notice above does not evidence any   	*/
/*	actual or intended publication of such source code.	*/

/*LINTLIBRARY*/
#include "shlib.h"
#include <stdio.h>

extern void free();
extern int isatty();
extern unsigned char _smbuf[][_SBFSIZ];
#if !u370
/* extern unsigned char *_stdbuf[]; */
extern unsigned char _sibuf[], _sobuf[];
#else
extern char *malloc();
#endif

void setbuf(register FILE *iop, char	*buf)
{
	register int fno = fileno(iop);  /* file number */

	if(iop->_base != NULL && iop->_flag & _IOMYBUF)
		free((char*)iop->_base - 4);	/* INTERNATIONAL */
	iop->_flag &= ~(_IOMYBUF | _IONBF | _IOLBF);
	if((iop->_base = (unsigned char*)buf) == NULL) {
		iop->_flag |= _IONBF; /* file unbuffered except in fastio */
#if u370
		if ( (iop->_base = (unsigned char *) malloc(BUFSIZ+8)) != NULL){
			iop->_flag |= _IOMYBUF;
			_bufend(iop) = (iop->_base += 4) + BUFSIZ; /* INTERNATIONAL */
		}
#else
		if (fno < 2) 	/* for stdin, stdout, use the existing bufs */
			/*_bufend(iop) = (iop->_base = _stdbuf[fno]) + BUFSIZ; */

			_bufend(iop) = (iop->_base = (fno == 0 ? _sibuf+4 : _sobuf+4)) + BUFSIZ ;
		
#endif

		else   /* otherwise, use small buffers reserved for this */
			_bufend(iop) = (iop->_base = _smbuf[fno]+4) + _SBFSIZ - 4;	/* INTERNATIONAL */
	}
	else {  /* regular buffered I/O, standard buffer size */
		_bufend(iop) = (iop->_base +=4)  + BUFSIZ - 4;	/* INTERNATIONAL */
		if (isatty(fno))
			iop->_flag |= _IOLBF;
	}
	iop->_ptr = iop->_base;
	iop->_cnt = 0;
}
