#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <libp.h>

extern int _abterm;

FILE *_pstreams[_NFILE_];
char *_filenames[_NFILE_];
int maxfiles;

#pragma startup fileinit 139
#pragma rundown closeall 11

void fileinit(void)
{
	_ll_init();
}

void closeall(void)
{
	int i;
	if (!_abterm)
		for (i=maxfiles-1; i >=0; i--) {
			fclose(_pstreams[i]);
		}
}
int _basefclose(FILE *stream,int release)
{
	int rv,i;
	if (stream->token == FILTOK && maxfiles) {
		int tempflag = stream->istemp;
		char *fname;
		fflush(stream);
		stream->token = (short)-1;
		if (maxfiles > 1) {
			for (i=0; i < maxfiles; i++)
				if (_pstreams[i] == stream) {
					fname = _filenames[i];
					_pstreams[i] = _pstreams[maxfiles-1];
					_filenames[i] = _filenames[maxfiles-1];
					break ;
				}
			maxfiles--;
		}
		rv = _ll_close(stream->fd);
		if (tempflag && fname)
			rv &= remove(fname);
		if (fname)
			free(fname);
		if (stream->flags & _F_BUF)
			free(stream->buffer);
		if (release)
			free(stream);
		if (!rv)
			return 0;
		else {
			return EOF;
		}
	}
	else {
		errno = _dos_errno = ENOENT;
		return EOF;
	}
}
int fclose(FILE *stream)
{
	return _basefclose(stream,1);
}