/*
 * $Copyright:	$
 * Copyright (c) 1984, 1985, 1986, 1987, 1988, 1989, 1990 
 * Sequent Computer Systems, Inc.   All rights reserved.
 *  
 * This software is furnished under a license and may be used
 * only in accordance with the terms of that license and with the
 * inclusion of the above copyright notice.   This software may not
 * be provided or otherwise made available to, or used by, any
 * other person.  No title to or ownership of the software is
 * hereby transferred."
 *
 */
/*	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.	*/

#ident	"@(#)libc-port:stdio/findiop.c	1.6"
/*	3.0 SID #	1.2	*/
/*LINTLIBRARY*/
#include "shlib.h"
#include <stdio.h>
#include <errno.h>

extern char *calloc();
extern void free();

extern FILE *_iobdynamic[];
extern FILE **_iobstart;
extern FILE **_iobend;

 /*
 *  
 *  Find a free FILE for fopen and various other routines.
 *  We have a fixed array called _iob that is intially used.  There is a dynamic
 *  structure of _NFILE number of *(FILE) that point to the corresponding _iob
 *  entry.  This dynamic structure is accessed using the _iobstart and _iobend
 *  global pointers.  (Pointing to the front and back of the list, respectively.)
 *  Whenever a process wants more than the normal _NFILE fd's, a setdtablesiz()
 *  has been called.  A new dynamic structure is calloc'd to have _NFILE more
 *  *(FILE) pointers, and the old pointers are copied in.  Any new FILE structs
 *  needed past the normal 20 are calloc'd.
 */

FILE *
_findiop()
{
	register FILE **iov;

	iov = _iobstart;
	while (*iov != NULL && _active(*iov))
		if (++iov >= _iobend) {
			if (_f_morefds() == 0) {
				errno = ENOMEM;
				return(NULL);
			}
			iov = _iobstart;	/* We've changed the table */
		}

	if (*iov == NULL)
		*iov = (FILE *)calloc(1, sizeof **iov);

	return(*iov);
}

_f_morefds()
{
	register FILE **iov;
	register FILE **fp;
	register FILE **start;
	int nfiles;

	nfiles = _iobend - _iobstart +  _NFILE;

	iov = (FILE **)calloc(nfiles, sizeof *iov);
	if (iov == NULL)
		return(0);
	
	start = iov;
	for (fp = _iobstart; fp < _iobend; )
		*iov++ = *fp++;

	if (_iobstart != _iobdynamic)
		free(_iobstart);
	_iobstart = start;
	_iobend = _iobstart + nfiles;
	return(1);

}
