/*
   Async file support. Sits on top of async.c (c) Stone, The SST
   Public domain. email c9107253@cs.newcastle.edu.au
*/

#include <exec/types.h>
#include <exec/memory.h>
#include <exec/ports.h>
#include <dos/dos.h>
#include <dos/dosextens.h>
#include <proto/exec.h>
#include <proto/dos.h>
#include <st/st_proto.h>


/** The following routines hide the port so your program
 ** never has to worry about ports at all */

/*********************************************************/
void			AEasyClose(struct AFileHandle *afh)
/*********************************************************
        Delete port if last file in list is closed
 *********************************************************/
{
struct APort *ap;
	if(!afh) return;
	ap = afh->APort;
	AClose(afh);
	if(!ap->First) ADeletePort(ap);
}

/*********************************************************/
struct AFileHandle
		*AEasyOpen(struct AFileHandle *af, char *name, long mode)
/*********************************************************
                 Open a file using AOpen
       Any open file handle from the required port
       should be supplied or NULL for initial port
 *********************************************************/
{
struct APort *ap;
struct AFileHandle *new_afh;
	if(!af) { if(!(ap = ACreatePort())) return(NULL); }
	else ap = af->APort;
	if(new_afh = AOpen(ap, name, mode)) return(new_afh);
	if(!ap->First) ADeletePort(ap);
	return(NULL);
}


/*********************************************************/
struct AFileHandle
		*AEasyMakeFD2AFD(struct AFileHandle *af, long fd)
/*********************************************************
       Make an AFileDescriptor from an ordinary fd
       Any open file handle from the required port
       should be supplied or NULL for initial port
 *********************************************************/
{
struct APort *ap;
struct AFileHandle *new_afh;
	if(!af) { if(!(ap = ACreatePort())) return(NULL); }
	else ap = af->APort;
	if(new_afh = AMakeFD2AFD(ap, fd)) return(new_afh);
	if(!ap->First) ADeletePort(ap);
	return(NULL);
}

/*********************************************************/
void			ASafeEasyClose(struct AFileHandle **afh)
/*********************************************************/
{ AEasyClose(*afh); *afh = NULL; }


