
/*
 *  DClose.C
 */

#include "lib.h"

void
DClose(_chan)
void *_chan;
{
    CHANN *chan = (CHANN *)_chan;
    IOSTD ior;
    IOSTD *io;
    IFDEBUG(int bogositylimit = 100;)

    IFDEBUG(printf("starting DClose(%lx)\n", _chan); sleep(1);)
    if(chan == NULL) {
    	return;
    }

    ior.io_Command = DNCMD_CLOSE;
    ior.io_Unit =  (struct Unit *)((ulong) chan->chan);
    ior.io_Offset = (ulong) chan;
    ior.io_Message.mn_ReplyPort = (PORT *)chan;
    PutMsg(chan->dnetport, (MSG *)&ior);
    IFDEBUG(printf("DCLose message put...\n");sleep(1);)
    ++chan->queued;
    chan->qlen = 0;   /* we want to flush the dnet queue */
    WaitQueue(chan, &ior);     /* wait until the queue is flushed */
    IFDEBUG(printf("WaitQueue() done...\n");sleep(1);)
    if(&(chan->rdylist) != NULL && !(IsListEmpty(&(chan->rdylist) )))
	while ((io = (IOSTD *)RemHead(&chan->rdylist)) != NULL ) {
	    io->io_Error = 1;
	    ReplyMsg((MSG *)io);
	}
    IFDEBUG(printf("chan->rdylist cleared...\n");sleep(1);)
    if(&chan->port != NULL)
	while ( ((io = (IOSTD *)GetMsg(&chan->port)) != NULL)
	    IFDEBUG(&& (bogositylimit-- > 0))
	) {
	    io->io_Error = 1;
	    ReplyMsg((MSG *)io);
	}
    IFDEBUG( if(bogositylimit <=0) printf("My BogoMeter broke!\n");)
    IFDEBUG(printf("chan->port cleared\n");sleep(1);)
    DeleteChannel(chan);
    IFDEBUG(printf("Channel deleted...\n");)
}
