#include <sys/types.h>
#include <sys/sysent.h>
#include <sys/time.h>
#include <errno.h>
#include "funcdef.h"
#include "../defs.h"
#include "../funcs.h"

struct tcpopen_func {
	int (_fastcall *proc)(short _far *);
} _near tcpopen_funcs[] = {
	0,
	tcpopen_init,
	tcpopen_shutdown,
	tcpopen_socket,
	tcpopen_info,
	tcpopen_accept,
	tcpopen_drain,
	tcpopen_release,
	tcpopen_eof,
	tcpopen_read,
	tcpopen_write,
	tcpopen_recv,
	tcpopen_sendto,
	tcpopen_select,
	0
};

#define N_FUNCS (sizeof (tcpopen_funcs) / sizeof (tcpopen_funcs[0]))

int
main(argc, argv, envp)
int argc;
char **argv;
char **envp;
{
	return 0;
}

int
rpc_entry(buf, size)
short _far *buf;
int size;
{
    struct tcpopen_func near *tfp;
    int i;

    tfp = &tcpopen_funcs[buf[0]];
    if ((unsigned)buf[0] >= N_FUNCS || !tfp->proc) {
	buf[0] = -1;
	buf[2] = NETERR_BADCALL;
	return 6;
    }
    i = (tfp->proc)(buf);
    if (i < 0) {
	buf[0] = i;
	buf[1] = errno;
	buf[2] = convert_error(errno);
	return 6;
    }
    return i;
}

int _fastcall
tcpopen_shutdown(buf)
short _far *buf;
{
    scloseall();
    return 0;
}

int _fastcall
tcpopen_select(buf)
short _far *buf;
{
    struct timeval ztime;
    int ret;
    fd_set ifds, ofds;

    ztime.tv_sec = 0;
    ztime.tv_usec = 0;
    ifds = *(fd_set _far *)&buf[2];
    ofds = *(fd_set _far *)&buf[4];
    ret = select(32, &ifds, &ofds, 0, &ztime);
    if (ret < 0)
	return ret;
    *(fd_set _far *)&buf[2] = ifds;
    *(fd_set _far *)&buf[4] = ofds;
    buf[0] = ret;
    return 12;
}

int _fastcall
tcpopen_release(buf)
short _far *buf;
{
    int ret;

    ret = sclose(buf[1] | FD_SOCKET);
    if (ret < 0)
	return ret;
    buf[0] = ret;
    return 2;
}

int _fastcall
tcpopen_eof(buf)
short _far *buf;
{
    int ret;

    ret = shutdown(buf[1] | FD_SOCKET, 1);
    if (ret < 0)
	return ret;
    buf[0] = ret;
    return 2;
}
