/*
 *		Cross Development System for Atari ST 
 *     Copyright (c) 1988, Memorial University of Newfoundland
 *
 */
#include 	<compiler.h>
#include	<osbind.h>
#include	<fcntl.h>
#include	<device.h>
#include	<stdlib.h>
#include 	<unistd.h>

int (*pipeclose_p) __PROTO((int fd)) = 0;

#ifdef DEBUG
#include <stdio.h>
#endif

int close(fd)
int	fd;
{
    int     oldfd;
    extern	int	errno;
    int		rval;
    struct _device	*dev;
    
    if ((dev = _dev_fd(fd)) && dev->close)
	return (*dev->close)(fd);
    oldfd=fd;
    fd = __OPEN_INDEX(fd);
    
    if ((fd >= 0) && (fd < __NHANDLES))
    {
	if (__open_stat[fd].pipe)
	{
	    if (oldfd < 3)
	    {
		__open_stat[fd].pipe = 0;
		rval = close(oldfd);
	    }
	    else 
		rval = (*pipeclose_p)(oldfd);
	    return(rval);
	}
	else 
	    if((__open_stat[fd].status == FH_ISAFILE) &&
	       (__open_stat[fd].filename))
	    	free(__open_stat[fd].filename);
	__open_stat[fd].status = FH_UNKNOWN;
	__open_stat[fd].append = 0;
	__open_stat[fd].nodelay = 0;
	__open_stat[fd].pipe = 0;
	__open_stat[fd].eclose = 0;
	__open_stat[fd].filename = (char *) 0;
    }
    
    if ((rval = Fclose(oldfd)) < 0) {
	errno = -rval;
	rval = -1;
    }
    
#ifdef DEBUG
    fprintf(stderr, "close(%d)->%d\n", (fd + __SMALLEST_VALID_HANDLE),
	    rval);
#endif
    return rval;
}

