#include <pctcp/types.h>
#include <pctcp/pctcp.h>
#include <pctcp/options.h>
#define MSW3
#include <pctcp/error.h>
#include "funcdef.h"
#include "../defs.h"

extern int _near neterrno;
extern int _near netsuberrno;

int
net_socket(type, addr)
int type;
struct net_addr _far *addr;
{
    int fd;
    struct addr tcp_addr;

    fd = net_getdesc();
    if (fd < 0) {
	net_perror("net_getdesc");
	return fd;
    }

    if (set_option(fd, 0, NET_OPT_NONBLOCKING, (char _far *)1, 0)) {
	net_perror("set_option");
	net_release(fd);
	return -1;
    }
    switch (type) {
	case NET_TYPE_TCP:
	    tcp_addr.protocol = 0;
	    type = STREAM;
	    break;
	case NET_TYPE_UDP:
	    tcp_addr.protocol = 0;
	    type = DGRAM;
	    break;
	default:
	    dfputs("unknown socket type\r\n");
	    return fd;
    }
    tcp_addr.lsocket = addr->socket;
    tcp_addr.fhost = addr->host;
    tcp_addr.fsocket = 0;

    if (net_listen(fd, type, &tcp_addr) < 0) {
	net_perror("net_listen");
	net_release(fd);
	return -1;
    }
    return fd;
}

void
net_perror(str)
char _near *str;
{
    dfputs(str);
    if (neterrno == NET_DOS_ERR) {
	dfputs(": System Error");
    } else {
	dfputs(": Error ");
	printd(neterrno);
    }
    dfputs("\r\n");
}
