
/*
 *  DOpen.C
 */

#include "lib.h"

PORT *
DOpen(host, portnum, txpri, rxpri)
char *host;
int txpri, rxpri;
uword portnum;
{
    IOSTD ior;
    CHANN *chan;

    if (rxpri > 126)
	rxpri = 126;
    if (rxpri < -127)
	rxpri = -127;
    if (txpri > 126)
	txpri = 126;
    if (txpri < -127)
	txpri = -127;
    if (host == NULL)
	host = "0";

    /* not sure this is necessary, safe, or even useful, but... */
    ior.io_Unit =  (struct Unit *)((ulong)portnum); 
    /* sets channel's io_Unit in MakeCannel */

    chan = (CHANN *)MakeChannel(&ior, host);  
    /* create the channel for the DNet communications */

    /* 
    ** connect up to the DNet 'server', tell it to open a connection
    ** to the other end 'server' 
    */

    if ( chan && chan->dnetport) {
	ior.io_Command = DNCMD_OPEN;  	/* we're opening a connection */
	ior.io_Unit = (struct Unit *)((ulong)portnum);  /* on this port */
	ior.io_Offset = (ulong)chan;     /* talk to this channel? */
	ior.io_Message.mn_ReplyPort = (PORT *)chan;  
					/* send replies to this channel */
	/* set priorities */
	ior.io_Message.mn_Node.ln_Pri = txpri;
	ior.io_Message.mn_Node.ln_Name= (char *)rxpri;

	/* send the message to the local DNet server's port */
	PutMsg(chan->dnetport, (MSG *)&ior);

	/* wait for its reply */
	WaitMsg(&ior);

	if (ior.io_Error == 0) {
	    chan->chan = (ulong)ior.io_Unit;
	    FixSignal(chan);
	    return((PORT *)chan);
	}
    } else {
       if(chan)  /* chan->dnetport == NULL */ 
       	    printf("DNetport for host \"%s\" not found!\n");
       IFDEBUG( printf("ACK! MakeChannel() failed!\n"); sleep(1);)
    }

    DeleteChannel(chan);
    return(NULL);
}

