#include <conio.h>
#include <signal.h>
#include <stdio.h>
#include "pcdefs.h"
#include "mbuf.h"
#include "netdef.h"
#include "protocol.h"
#include "in.h"
#include <malloc.h>
#include "net.h"
#include "config.h"

struct ebuf _far * _far Sgeteb();
int far configure(char far *, struct conf far *);
unsigned long far Sdomain();
struct tcpport tcpout;
u_char	buf[1024];
u_char	inbuf[1024];
int onint();

main(argc, argv)
char **argv;
{
	int	i;
	int	s;
	int	wrote;
	struct conf far *cp;
	struct sockaddr saddr;
	struct ebuf _far *ep;
	unsigned long host;
	u_char *inp;
	int c;

	if (argc != 3) {
		fprintf(stderr, "Usage: call host port\n");
		exit(1);
	}
	cp = SgetScon();
	if (configure((char far *)0, cp) < 0) {
		printf("ERROR: reading config.tel\n");
		exit (-1);
	}
	i = Snetinit();
	if (i < 0) {
		printf("Snetinit returns %d\n", i);
		exit (-1);
	}
	host = Sgetname();
	inp = Sgetdomain();
	printf("nameserver=%lx, domain=\"%s\"\n", host, inp);
	signal(SIGINT, onint);
#ifdef notdef
	printf("Packet info:\n");
	printf("    version %x\n", pk_info.packet_version);
	printf("    class %x\n", pk_info.packet_class);
	printf("    type %x\n", pk_info.packet_type);
	printf("    ifnumber %x\n", pk_info.packet_ifnumber);
	printf("    name %Fs\n", pk_info.packet_name);
	printf("    extended %x\n", pk_info.packet_extended);
	printf("ip handle = %x\n", ip_handle);
	printf("arp handle = %x\n", arp_handle);
#endif
	ep = Sgeteb();
	printf("ebaddr 0x%x, len = %d\n", (int)ep->start_addr, (int)ep->count);

	i = Sdominit();
	if (i < 0) {
		printf("Sdominit returns %d\n", i);
		goto err;
	}

	host = Sdomain(argv[1], 36);
	printf("Sdomain(\"%s\") returns %lx\n", argv[1], host);
	if (!host) {
		printf("%s: unknown host\n", argv[1]);
		goto err;
	}

	s = Socket(SOCK_STREAM, &saddr, 0, (struct port far *)&tcpout);
	if (s < 0) {
		printf("send Socket returns %d\n", s);
		Snetshut();
		exit(-1);
	}
	saddr.port = 0;
	if (SoBind(s, &saddr) < 0) {
		printf("send SoBind returns errord\n");
		Snetshut();
		exit(-1);
	}
	saddr.addr = host;
	saddr.port = htons(atoi(argv[2]));
	i = SoConnect(s, &saddr);
	if (i < 0) {
		printf("SoConnect returns %d\n", i);
		goto err;
	}
	inp = inbuf;
	for (;;) {
		netsleep();
		if (kbhit()) {
			c = getche();
			if (c == '\r')
				c = '\n';
			if (inp == inbuf && c == 26) {
				SoClose(s);
				continue;
			}
			*inp++ = c;
			if (c == '\n') {
				i = SoWrite(s, inbuf, inp - inbuf);
				inp = inbuf;
			}
		}
		i = SoRead(s, buf, sizeof buf);
		if (i < 0)
			break;
		if (i)
			write(1, buf, i);
	}
leave:
	i = SoClose(s);
	printf("test: after leave Soclose returns %d\n", i);
err:
	printf("hit any key to continue\n");
	while (!kbhit())
		;
	Sdomshut();
	Snetshut();
	ep = Sgeteb();
	printf("ebaddr 0x%x, len = %d\n", (int)ep->start_addr, (int)ep->count);
}

onint()
{
	Snetshut();
	exit(1);
}
