/*
 *  WaitQueue.C
 */

#include "lib.h"

/* wait until all IORequests on a channel's port are cleared, except
** for the one called as skipior
*/

short
WaitQueue(_chan, skipior)
void *_chan;
IOSTD *skipior;
{
    CHANN *chan = (CHANN *)_chan;
    IOSTD *io;
    ulong waitmask;

    short error = 0;
    while (chan->queued > chan->qlen) {  /*  while queue size > maxqueuesize */
	IFDEBUG(printf("Waiting for something on port %lx\n", &(chan->port));)
	waitmask = SIGBREAKF_CTRL_C ;
	waitmask |= (1 << chan->port.mp_SigBit);
	Wait( waitmask );        
	io = (IOSTD *)GetMsg( & (chan->port) );
	if(io == NULL){
	    IFDEBUG(fprintf(stderr, "NULL from GetMsg(chan->Port)!\n");)
	    error = -6;
	    break;
	}

	/* message has been processed and replyd, remove it */
	if ( io->io_Message.mn_Node.ln_Type == NT_REPLYMSG) {
	    if (error == 0)
		error = io->io_Error;
	    if (io != skipior) {
		if (io->io_Length)
		    FreeMem(io->io_Data, io->io_Length);
		FreeMem(io, sizeof(IOSTD));
	    }
	    --chan->queued;
	} else {
	    /* put message back onto the end of the channel's 
	    ** rdylist */
	    AddTail( &(chan->rdylist), (NODE *)io);
	}
    }
    return(error);
}
