/* Asyncronous IO routines */


#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>

long	out = NULL, in = NULL, err = NULL;
char	prg[40];

main(int argc, char *argv[])
{
struct AFileHandle *afh = NULL, *afh2 = NULL;
char	buf[2][100], buf2[1000];
long	n, w, n2;

	out = Output();
	in	= Input();
	err = Open("*",MODE_OLDFILE);
	fpf(err, "%08lx %08lx %08lx\n", out, err, in);

	spf(prg, sizeof(prg), "%s[%s]", argv[0], FindTask(NULL)->tc_Node.ln_Name);

/* OPEN THE FILE */

/*	if(!(afh = AEasyOpen(NULL, argv[1], MODE_OLDFILE))) {
		fpf(err,"Couldn't open '%s' for input\n", argv[1]);
		goto endit;
	} */

	if(!(afh2 = AEasyMakeFD2AFD(NULL, in))) {
		fpf(err,"Couldn't open input\n");
		goto endit;
	} 


	if(!(afh = AEasyOpen(afh, argv[1], MODE_OLDFILE))) {
		fpf(err,"Couldn't open '%s' for input\n", argv[1]);
		goto endit;
	}

	fpf(err,"%s: Opened the files ok!\n", prg);

	fpf(err,"Trying to change %s into raw mode\n", argv[1]);
	ASendPacket(afh, ACTION_SCREEN_MODE, 1, 0, 0, 0);
	n = AResultWait(afh2);
	fpf(err,"mode change result = %ld\n",n);


/** START A READ FROM THE SECOND FILE  */
	ARead(afh2, buf2, 1000);

/** READ THE ENTIRE FIRST FILE & PRINT */
	fpf(out,"Double buffered reading of '%s'\n", argv[1]);
	w = 0;
	ARead(afh, buf[w], 100);
	for(n = 1; n ; ) {
		while((AStatus(afh)) == ASTATUS_BUSY) Write(out,"x",1);
		n = ARead(afh, buf[1-w], 100);
		fpf(out,"%ld ",n);
		if( n > 0 )
		{ Write(out, buf[w], n); fpf(out, "lastchar: %ld\n", buf[w][n-1]); }
		w = 1 - w;
	}

/** SEE WHAT WAS READ FROM THE OTHER FILE */
	fpf(out,"\nThe following was read from '%s' also:\n", argv[2]);
	Write(out, buf2, AResultWait(afh2));

endit:
	SafeClose(&err);
	ASafeEasyClose(&afh);
	ASafeEasyClose(&afh2);

	return(0);
}

