/*---- Included header files ----*/
#include <a:libc.h>
#include <a:fcntl.h>

/*---- Macros ----*/
#define TRUE	-1
#define FALSE	0

/*---- Structures ----*/

/* we have a simple queue of files to send out via the AUX port */
struct file_queue
	{
	char	active;		/* has it been erased or not?  */
	char	filename[15];
	} the_queue[10] =	/* a file queue ten files long */
	{0,"",0,"",0,"",0,"",0,"",0,"",0,"",0,"",0,"",0,""};


/*---- Variables ----*/

int wokenup	= FALSE;	/* flag whether we have a spool request */
int file_open	= FALSE;	/* are we working on a file             */
int fd;				/* the file descriptor			*/
int i=0;			/* general-purpose index 		*/
int index;			/* index into buffer for next byte 	*/
int top;			/* index of top byte read in buffer	*/ 
char buffer[1024];		/* the buffer itself			*/


/* as we have no heap, we cannot use buffered file I/O and, of course, we
cannot MALLOC or FREE */

/*--------------------------------------------------------------------------*/
rsx_entry(de,bc)	/* the entrypoint to the RSX 			    */
struct rsxpb	/* as defined by Digital Research */
	{
	char	func;
	char	numparms;
	char	*filename;
	} *de;
int bc;
{
if ((bc & 0x00FF) == 60)	/* then it may be a 'wake up' request */
	{ /* so service the special RSX call */
	/* now, is it our call or another one? */
	if (de->func != 5) return(); 	/* if it is not ours then go home */
	/* firstly, see if there is a slot in the queue for the filename  */
	for (i=0; i<10; i++)	if (!(the_queue[i].active)) break;
	if (i==10) return (FALSE); 	/* return false if no slot 	  */
	strcpy (the_queue[i].filename,de->filename);
	the_queue[i].active = TRUE;	/* put the file in the queue      */
	wokenup=TRUE;
	return(TRUE);
	}
else	/* then it was just another bdos call */
	{
	if (!(wokenup)) return();	/* nothing to do */
	if (!(bdos(8,0))) return();	/* if not ready to transmit, do not */
	/* if we got here, the auxout is ready */ 
	if (file_open)
		{
		char ch;
		if (index < top) 
			{
			bdos(4,ch=buffer[index++]);
			if (ch == 0x1A) index=top;
			}
		else /* read in a new buffer full */
			{
			if (!(top=read (fd,buffer,1024))) 
				{
				close(fd);
				file_open=FALSE;	
				index=0;
				return();
				}
			else index=0;
			}
		}
	else	/* the file was not open */
		{
		for (i=0; i<10; i++)	if (the_queue[i].active) break;
		if (i==10)
			{
			wokenup = FALSE; /* we have done all we were woken to do */
			return ();	 /* return as no file to do */
			}
		else
			{
			the_queue[i].active=FALSE;
			fd=open(the_queue[i].filename,O_RDONLY);
			file_open = (!(fd==-1)); /*if no error then file open*/
			}
		} /* end of else file was not open */
	} /* end just another BDOS call */
}
