/*
 * |-----------------------------------------------------------|
 * | 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: fopen.c,v 1.13.2.1 92/06/24 14:01:31 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"
#include <fcntl.h>
#include <errno.h>

extern int open(), fclose();
extern long lseek();
extern FILE *_findiop();
static FILE *_endopen();

#if defined(__STDC__)

FILE     *fopen(const char *file, const char *mode)

#else

FILE * fopen(file,mode)
char *file, *mode;

#endif
{
	return (_endopen(file, mode, _findiop()));
}

#if defined(__STDC__)

FILE     *freopen(const char *file, const char *mode, FILE *iop)

#else

FILE *
freopen(file, mode, iop)
char	*file, *mode;
register FILE *iop;

#endif
{
	(void) fclose(iop); /* doesn't matter if this fails */
	return (_endopen(file, mode, iop));
}

static FILE * _endopen( char *file, char *mode, register FILE *iop)
{
	register int	plus, oflag, fd;

	if (iop == NULL || file == NULL || file[0] == '\0') {
#ifdef	SYSTYPE_POSIX
		errno = ENOENT;
#endif
		return (NULL);
	}
#if defined(__STDC__)
	if (mode[1] == 'b')
	  plus = (mode[2] == '+');
	else
#endif
	  plus = (mode[1] == '+');
	switch (mode[0]) {
	case 'w':
		oflag = (plus ? O_RDWR : O_WRONLY) | O_TRUNC | O_CREAT;
		break;
	case 'a':
		oflag = (plus ? O_RDWR : O_WRONLY) | O_APPEND | O_CREAT;
		break;
	case 'r':
		oflag = plus ? O_RDWR : O_RDONLY;
		break;
	default:
		return (NULL);
	}
	fd = open(file, oflag, 0666);
	if (fd < 0 || fd >= _NFILE) {
		if (fd >= _NFILE ) close(fd);
		return (NULL);
	}
	iop->_cnt = 0;
	iop->_file = fd;
	iop->_flag = plus ? _IORW : (mode[0] == 'r') ? _IOREAD : _IOWRT;
	if (mode[0] == 'a')   {
		if (!plus)  {
			/* if update only mode, move file pointer to the end
			   of the file */
			if ((lseek(fd,0L,2)) < 0)  {
				return NULL;
			}
		}
	}
	_bufend(iop) = iop->_base = iop->_ptr = NULL;
	return (iop);
}
