/* This is the client that goes on the host with the xserver.  It
 * will figure out what port to connect to, it will initialize
 * everything, and then it will connect to the remote server.
 * Or, at least it will TRY to....  And keep trying until it succeeds
 */

#include <stdio.h>
#include <conndefs.h>
#include <netdb.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/types.h>
#include <string.h>
#include <strings.h>

extern int handler_int();

extern int xsocket;
extern int news;

char *host;

static char *whoami;

usage()
{
    fprintf(stderr, "usage: %s -h hostname [-n]\n", whoami);
    fprintf(stderr, "	-n:	Use NeWS server, not X server\n");
    exit(1);
}

main (argc, argv)
int argc;
char *argv[];
{
    char envirbuf[256];
    char *envptr;
    int i;
    extern char *optarg;
    extern int optind;
    int un = 0;

    whoami = argv[0];

    while ((i = getopt(argc, argv, "nh:")) != -1) 
	switch (i) {
	case 'h':
	    host = optarg;
	    break;
	case 'n':
	    news = 1;
	    break;
	default:
	    usage();
	}

    if (host == NULL)
	usage();

    clear_listeners();

    getenv("DISPLAY", envirbuf);
    envptr = rindex(envirbuf, ':');

    if (*envirbuf == '\0') {
	fprintf(stderr, "%s: No DISPLAY variable. Assuming 0\n", whoami);
	un = 0;

    } else {
	if (envptr == NULL)
	    envptr = envirbuf;
	else
	    envptr++;

	un = atoi (envptr);
    }
/*    xsocket = un + (news) ? 2000 : 6000;*/
    xsocket = un + 6000;

    init_conns();
    conn_list[0].inuse = INUSE;
    conn_list[0].fd = tcp_init();
    if (conn_list[0].fd < 0) {
	fprintf(stderr, "%s: Error connecting to host %s\n", whoami, host);
	exit(1);
    }
    add_listener(conn_list[0].fd);
	
    signal(SIGPIPE, SIG_IGN);
    signal(SIGINT, handler_int);

    loop();
}
