/* 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 <signal.h>
#include <string.h>
#include <strings.h>

int xlistener;

char *host = "Using TCP";
static char *whoami;
extern int debug;

usage()
{
    fprintf(stderr, "usage: %s [-d displaynumber]\n", whoami);
    exit(1);
}

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

    whoami = argv[0];

    while ((i = getopt(argc, argv, "d:")) != -1) 
	switch (i) {
	case 'd':
	    un = atoi(optarg);
	    break;
	default:
	    usage();
	}

    clear_listeners();
    init_conns();

    xsocket = 6000 + un;

    if ((xlistener = open_listener(xsocket)) < 0) {
	fprintf(stderr, "%s: Couldnt open X Listener %d\n", whoami, xsocket);
	exit(1);
    }

    add_listener(xlistener);

    conn_list[0].inuse = INUSE;

    if(debug)
	printf("Waiting for connection...\n");

    conn_list[0].fd = tcp_init();
    if (conn_list[0].fd < 0) {
	fprintf(stderr, "%s: Error getting remote connection\n", whoami);
	exit(1);
    }
    add_listener(conn_list[0].fd);
	
    signal(SIGPIPE, SIG_IGN);

    loop();
}
