#include <stdio.h>
#include "defs.h"
#include "rpc.h"
#include "funcs.h"

char _far *net_shared;
int net_shared_size;
unsigned char net_handle;

int
net_open(file)
const char *file;
{
    int i;
    int addr;
    short buf[5];

    i = rpc_init(file);
    if (i < 0) {
	perror(file);
	neterrno = NETERR_ERRNO;
	return -1;
    }
    net_handle = i;
    buf[0] = FUNC_INIT;
    i = rpc_call(net_handle, sizeof buf, 2, buf);
    if (!i) {
	neterrno = NETERR_ERRNO;
	return -9;
    }
    /* The buffer is organized like this:
     * (short) word 0:	status
     *		    1:  pad
     *		    2:  offset of shared address
     *		    3:	segment of shared address
     *		    4:	size of shared buffer
     */
    switch (buf[0]) {
	case 0:
	    break;
	case -1:
	    neterrno = buf[2];
	    if (neterrno == NETERR_ERRNO)
		map_errno(buf[1]);
	    net_perror("net init");
	default:
	    return buf[0];
    }
    /* convert to real address (20 bits) */
    net_shared_size = buf[4];
    addr = (buf[3] << 4) + buf[2];
    i = get_real_window(addr & 0xffff0, (buf[4] + 15 + (addr & 0x0f)) & 0xfff0);
    if (!i) {
	neterrno = NETERR_ERRNO;
	return -10;
    }
    *(int *)&net_shared = addr & 0x000f;
    ((short *)&net_shared)[2] = (short)i;

    return 0;
}

void
net_shutdown()
{
    short buf[1];

    buf[0] = FUNC_SHUTDOWN;
    rpc_call(net_handle, 0, 2, buf);
}
