
/*
 *  MakeChannel.C
 *
 *  (internal routine)
 */

#include "lib.h"

/* this is rather bogus, and completely unused... */
short	DUseSignal = -1;

/* uh, use CreatePort in this? */

void *
MakeChannel(ior, host)
IOSTD *ior;
char *host;
{
    CHANN *chan = AllocMem(sizeof(CHANN), MEMF_PUBLIC|MEMF_CLEAR);

    IFDEBUG(printf("Making a channel to host %s\n", host);)

    if(chan == NULL) return NULL;

    /* create and initialize channel's message port */

    chan->port.mp_Node.ln_Type = NT_MSGPORT; /* it's a message port */

    /*  set the signal that this channel's port will use */
    if (DUseSignal >= 0)
	chan->port.mp_SigBit = DUseSignal;
    else 
    {
        int sigbit;
        if((sigbit = AllocSignal(-1)) != -1)
	    chan->port.mp_SigBit = sigbit;
	else {
	    printf("MakeChannel(): Failed to AllocSignal for new channel!\n");
	    FreeMem( chan, sizeof(CHANN));
	    return NULL;
	}
    }

    chan->port.mp_SigTask = FindTask(NULL);  /* signals will go to this task */

    NewList(&chan->port.mp_MsgList);   /* Initialize this port's list */

    NewList(&chan->rdylist);  	      /* Init list of items ready to be read */
    chan->chan = (ulong)ior->io_Unit; /* set the the unit of the new channel */
    ior->io_Offset = (ulong)chan;      /* Uh, why? */

    if (host) {
	char buf[sizeof(DNETPORTNAME)+32];
	sprintf(buf, "%s%s", DNETPORTNAME, host);
	Forbid();
	ior->io_Message.mn_ReplyPort = FindPort(buf);
	Permit();
	IFDEBUG(printf("Set ior's reply port to port for \"%s\"\n", buf);)
    }
    chan->dnetport = ior->io_Message.mn_ReplyPort;
    IFDEBUG(if(chan->dnetport == NULL)printf("dnetport not set!\n");)

    return((void *)chan);
}

void
DeleteChannel(_chan)
void *_chan;
{
    CHANN *chan = (CHANN *)_chan;

    IFDEBUG(printf("Deleting channel %lx\n", chan);)
    if (chan->port.mp_SigBit != DUseSignal)
	FreeSignal(chan->port.mp_SigBit);
    IFDEBUG(printf("channel signal freed\n", chan);)
    FreeMem(chan, sizeof(CHANN));
    IFDEBUG(printf("channel freed (%d byts) \n", sizeof(CHANN) );)
}
