#include "X11/Xlib.h"
#include "X11/Xutil.h"
#include "X11/Xos.h"
#include "X11/Xatom.h"
#include "X11/keysym.h"
#include "X11/keysymdef.h"
#include "XInput.h"

#include <stdio.h>
char       *sprintf();
#include <sys/types.h>
#include <sys/time.h>


#include <math.h>
#define short2long(x) (long) (x & 0x00008000) >> 15 ? x | 0xffff0000 : x

#include "bitswap.h"

#define BITMAPDEPTH 1
/* from XPError.c */
#define XSetDeviceFocus_code			21

 /*
  * the following is stolen from the x consortium's xinput tests. these data
  * structs allow the X proto error handler to print out sensible messages
  */
char *ext_errors[] = {"BadDevice","BadEvent","BadMode","DeviceBusy","BadClass"};

char *std_errors[] = {"Success","BadRequest","BadValue","BadWindow","BadPixmap",
		"BadAtom","BadCursor","BadFont","BadMatch","BadDrawable",
		"BadAccess","BadAlloc","BadColor","BadGC","BadIDChoice",
		"BadName","BadLength","BadImplementation"};

char *extfuncs[] = {"undefined", "GetExtensionVersion","ListInputDevices",
"OpenDevice", "CloseDevice","SetDeviceMode","SelectExtensionEvent",
"GetSelectedExtensionEvents", "ChangeDeviceDontPropagateList",
"GetDeviceDontPropagateList","GetDeviceMotionEvents", "ChangeKeyboardDevice",
"ChangePointerDevice","GrabDevice","UngrabDevice", "GrabDeviceKey",
"UngrabDeviceKey","GrabDeviceButton","UngrabDeviceButton", "AllowDeviceEvents",
"GetDeviceFocus","SetDeviceFocus", "GetFeedbackControl",
"ChangeFeedbackControl","GetDeviceKeyMapping","ChangeDeviceKeyMapping",
"GetDeviceModifierMapping","SetDeviceModifierMapping","GetDeviceButtonMapping",
"SetDeviceButtonMapping","QueryDeviceState","SendExtensionEvent"};

#define PI 3.141593

Display    *display;
int         screen;
GC          gc;
unsigned int width = 250,
            height = 400;
unsigned int width2 = 450,
            height2 = 450;
unsigned int width3 = 1100,
            height3 = 800;
int         button_device,
            dial_device,
            lp_device;
Window      dial_win,
            button_win,
            lp_win,
            focus_return;
int         revert_to_return;
Time        focus_time_return;
XDevice    *db_handle,
           *lp_handle;
Cursor      lp_cursor;


extern char *optarg;
extern int  optind,
            opterr;

#define SMALL 1
#define OK 0

/* getopt variables */
extern char *optarg;
extern int  optind,
            opterr;
int         debug_level = 0;
void        debug();
int         o;

int         grab;
int         focus;		/* focus this winodow */
int         none;		/* pitch all input */
int         pointerroot;	/* root gets it */
int         followkey;		/* follow the keyboard focus */
int         closing;		/* about to inconify don't set focus */
int         show_lp,
            xhair_x = 1152 / 2,
            xhair_y = 900 / 2;
int         geom_x = 0,
            geom_y = 0;
char        title[256];

/* dials information used to draw and remember last state */

XPoint      centers[8];
XPoint      endpts[8] = {0, 0, 0, 0, 0, 0, 0, 0,};
int         dia;
float       angles[8] = {PI, PI, PI, PI, PI, PI, PI, PI,};
float       new;

int         side;

/* codes for the extension events - dynamically assigned by server */
int         qmajor,
            qminor,
            qfirsterror;
int         error_code,
            expect = Success;
int         motion_notify_type;
XEventClass db_motion_notify_class,
            lp_motion_notify_class;
int         button_press_type;
XEventClass db_button_press_class,
            lp_button_press_class;
int         button_release_type;
XEventClass db_button_release_class,
            lp_button_release_class;
int         device_focusin_type;
XEventClass db_device_focusin_class,
            lp_device_focusin_class;
int         device_focusout_type;
XEventClass db_device_focusout_class,
            lp_device_focusout_class;
int         db_codes[5];	/* the extension events requested */
int         lp_codes[5];

extern      _Xdebug;

void
main(argc, argv)
    int         argc;
    char      **argv;
{
    XEvent      report;
    char       *display_name = "";
    int         handle_x_errors();

    XID         dial_id,
                lp_id;
    int         i;
    int 	lp_motion_count;
    time_t start, stop;

    /* _Xdebug = 1;		 slows things down */

    /*
     * since this program tests so many variations of device, focus etc
     * collect them
     */
    options(argc, argv);

    XSetErrorHandler(handle_x_errors);

    if ((display = XOpenDisplay(display_name)) == NULL) {
	(void) fprintf(stderr, "Display no good.\n");
	exit(-1);
    }

    /*
     * check that the extension is present and possibly print out voluminious
     * data about it
     */
    extensions(&dial_id, &lp_id);

    if (dial_device || button_device)
	db_handle = XOpenDevice(display, dial_id);
    if (lp_device)
	lp_handle = XOpenDevice(display, lp_id);

    /*
     * set properties and create window(s)
     */
    window_properties(argc, argv);

    /*
     * figure out the event codes - because they are not manifest constants
     * and prepare to select for the appropriate ones
     */
    event_codes();

    /*
     * select for the correct set(s) of  events and map window
     */
    prep_for_events();

    /* Process events */
    while (1) {
	XNextEvent(display, &report);
	if (report.type == motion_notify_type) {
	    XDeviceMotionEvent *motionEvent = (XDeviceMotionEvent *) & report;

	    motion_report(motionEvent);
	    if (db_handle && (motionEvent->deviceid == db_handle->device_id)) {
		for (i = 0; i < motionEvent->axes_count; i++) {
		    debug(3, "     axis[%d] = %d\n", i + motionEvent->first_axis,
			  short2long(motionEvent->axis_data[i]));
		    new =
			(PI * (((float) (short2long(motionEvent->axis_data[i])
				* 2) / 21845.)));
		    /* 65536 / 3 = 21845 
		    new =
			(PI * (((float) (motionEvent->axis_data[i] * 2) / 21845.)));
		    */
		    if ((fabs(new) > (.0001)) || (fabs(new) < (-.0001))) {
			debug(3, "new angle %2f\n", new);
			angles[i + motionEvent->first_axis] -= new;
			indicator((int) (i + motionEvent->first_axis), 0);
		    }
		}
	    } else if (show_lp) {
		Window *root_ret, *child_ret;
		int root_x, root_y, win_x, win_y;
		unsigned int *keys_buttons;
		XQueryPointer(display, lp_win, &root_ret, &child_ret,
			&root_x, &root_y, &win_x, &win_y, 
			&keys_buttons);
			
		if (motionEvent->first_axis == 0) {
		    xhair_x = short2long(motionEvent->axis_data[0]);
		     xhair_x = xhair_x - root_x  ;
		    XWarpPointer(display, None, None, None, None,
				 None, None,
				 xhair_x,
				 0);
		} else {
		    xhair_y = short2long(motionEvent->axis_data[0]);
	 	    xhair_y = xhair_y - root_y ;
		    XWarpPointer(display, None, None, None, None,
				 None, None, 0,
				 xhair_y);
		}
		debug(2, "Cross hair cursor x %d y %d\n", xhair_x, xhair_y);
	    } else {
		lp_motion_count++;
	    }
	} else if ((report.type == button_press_type) ||
		   (report.type == button_release_type)) {
	    XDeviceButtonEvent *buttonEvent =
	    (XDeviceButtonEvent *) & report;
	    XTextItem   text_item;
	    char        button_number[4];

	    button_report(buttonEvent);

	    if (db_handle && (buttonEvent->deviceid == db_handle->device_id)) {
		{
		    XLedFeedbackControl fs;

		    fs.class = LedFeedbackClass;
		    fs.led_mask = 1 << (buttonEvent->button - 1);
		    fs.led_values = report.type == button_press_type ?
			fs.led_mask : 0;
		    XChangeFeedbackControl(display, db_handle, DvLed, &fs);
		}
		for (i = 0; i < buttonEvent->axes_count; i++) {
		    debug(3, "     axis[%d] = % d \n ", i + buttonEvent->first_axis,
			  (short) buttonEvent->axis_data[i]);
		}
		text_item.chars = button_number;
		(void *) sprintf(text_item.chars, "%d", buttonEvent->button);
		if (buttonEvent->button <= 9)
		    text_item.nchars = 1;
		else
		    text_item.nchars = 2;
		text_item.delta = 0;
		text_item.font = (XID) NULL;
		if (buttonEvent->type == button_press_type) {
		    XFillRectangle(display, button_win, gc,
				   button_pos[buttonEvent->button].x + 2,
				   button_pos[buttonEvent->button].y + 2,
				   side - 3, side - 3);
		    XSetForeground(display, gc, WhitePixel(display, screen));
		    XDrawText(display, button_win, gc, button_pos[buttonEvent->button].x + side / 3,
			      button_pos[buttonEvent->button].y + side / 3, text_item, 1);
		    XSetForeground(display, gc, BlackPixel(display, screen));
		} else {
		    XSetForeground(display, gc, WhitePixel(display, screen));
		    XFillRectangle(display, button_win, gc,
				   button_pos[buttonEvent->button].x + 2,
				   button_pos[buttonEvent->button].y + 2,
				   side - 3, side - 3);
		    XSetForeground(display, gc, BlackPixel(display, screen));
		    XDrawText(display, button_win, gc, button_pos[buttonEvent->button].x + side / 3,
			      button_pos[buttonEvent->button].y + side / 3, text_item, 1);
		}
	    } else if (lp_handle && 
		(buttonEvent->deviceid == lp_handle->device_id)) {
		/* count the motion events between a press and a release in
		order to time them */
		if (buttonEvent->type == button_press_type) {
	   		start = time(&start);
			lp_motion_count = 0;
			show_lp = 0;
			}
		else {
	   		stop = time(&stop);
			show_lp = 1;
			printf("%d motion events in %d seconds\n",
				lp_motion_count, stop - start);
			}
		
	    }
	} else {
	    debug(2, "Other event type = %X\n", report.type);
	    fflush(stderr);
	    switch (report.type) {
	    case Expose:
		while (XCheckTypedEvent(display, MapNotify, &report));
		if (report.xany.window == dial_win) {
		    draw_dials(dial_win, gc, width, height);
		    for (i = 0; i < 8; i++)
			indicator(i, 1);
		    dofocus(db_handle, dial_win);
		} else if (report.xany.window == button_win) {
		    draw_buttons(button_win, gc, width2, height2);
		    dofocus(db_handle, button_win);
		    closing = 0;
		} else {
		    dofocus(lp_handle, lp_win);
		    show_lp++;
		}
		break;
	    case MapNotify:
		while (XCheckTypedEvent(display, MapNotify, &report));
		if (report.xany.window == dial_win) {
		    draw_dials(dial_win, gc, width, height);
		    for (i = 0; i < 8; i++)
			indicator(i, 1);
		    dofocus(db_handle, dial_win);
		} else if (report.xany.window == button_win) {
		    draw_buttons(button_win, gc, width2, height2);
		    dofocus(db_handle, button_win);
		    closing = 0;
		} else {
		    dofocus(lp_handle, lp_win);
		    show_lp++;
		}
		break;

	    case EnterNotify:
		while (XCheckTypedEvent(display, EnterNotify, &report));
		if (followkey > 2 && !closing) {
		    if (button_device)
			i = XSetInputFocus(display, button_win,
					   RevertToPointerRoot, CurrentTime);
		    if (dial_device)
			i = XSetInputFocus(display, dial_win,
					   RevertToPointerRoot, CurrentTime);
		    if (lp_device)
			i = XSetInputFocus(display, lp_win,
					   RevertToPointerRoot, CurrentTime);
		}
		if (followkey)
		    followkey++;
		break;
	    case VisibilityNotify:
		if ((report.xany.window == lp_win) &&
			(report.xvisibility.state == VisibilityUnobscured)) {
		    int         numer,
		                denom,
		                thresh;

		    dofocus(lp_handle, lp_win);
		    show_lp = 1;
		    XDefineCursor(display, lp_win, lp_cursor);
		    XGetPointerControl(display, &numer, &denom, &thresh);
		    debug(2, "numer %d denom %d thresh %d \n", numer, denom, thresh);
		    XGetPointerControl(display, &numer, &denom, &thresh);
		    fprintf(stderr, "numer %d denom %d thresh %d \n", numer, denom, thresh);
		}
		break;
	    case UnmapNotify:
		if (report.xany.window == button_win &&
			followkey < 2)
		    closing = 1;
		if (report.xany.window == lp_win)
		    show_lp = 0;
		break;
	    case ButtonPress:
		if (dial_device | button_device)
		    XCloseDevice(display, db_handle);
		if (lp_device)
		    XCloseDevice(display, lp_handle);
		XUngrabPointer(display, CurrentTime);
		XCloseDisplay(display);
		exit(0);
		break;
	    }
	}
    }
}

draw_dials(win, gc, window_width, window_height)
    Window      win;
    GC          gc;
    unsigned int window_width,
                window_height;
{
    int         x,
                y,
                i,
                j,
                ctr;
    unsigned int width,
                height;
    XTextItem   text_item;
    char        dial_number[32];

    XSetFunction(display, gc, GXcopy);
    ctr = 0;
    width = (window_width * 7 / 10) / 2;
    height = (window_height * 65 / 100) / 4;
    if (width < height)
	height = width;
    else
	width = height;
    dia = (width / 2) - 2;
    for (i = 0; i < 2; i++) {
	if (i)
	    x = (window_width * 9 / 10) - width;
	else
	    x = window_width / 10;
	y = window_height / 10;
	for (j = 0; j < 4; j++) {
	    XDrawArc(display, win, gc,
		     x, y, width, height, 0, 360 * 64);
	    centers[ctr].x = x + width / 2;
	    centers[ctr].y = y + width / 2;
	    (void *) sprintf(dial_number, "%d", ctr);
	    text_item.nchars = 1;
	    text_item.chars = dial_number;
	    text_item.delta = 0;
	    text_item.font = (XID) NULL;
	    XDrawText(display, dial_win, gc, centers[ctr].x - 10,
		      centers[ctr].y - 10, text_item, 1);
	    ctr++;
	    y += height + (window_height * 5 / 100);
	}
    }
    XDrawPoints(display, win, gc, centers, 8, CoordModeOrigin);
}


draw_buttons(win, gc, window_width, window_height)
    Window      win;
    GC          gc;
    unsigned int window_width,
                window_height;
{
    int         x,
                y,
                i,
                j;
    unsigned int width,
                height;
    XTextItem   text_item;
    char        button_number[32];

    XSetFunction(display, gc, GXcopy);
    width = ((float) window_width * (60. / 100.) / 6.);
    height = ((float) window_height * (60. / 100.) / 6.);
    if (width < height)
	height = width;
    else
	width = height;
    side = width;
    for (i = 0; i < 6; i++) {
	for (j = 0; j < 6; j++) {
	    if (j == 0) {
		if (i == 0) {	/* no buttons in corners */
		    x = window_width / 12;
		    y = (window_height / 12) + side + window_width * 4 / 100;
		} else {
		    x += side + window_width * 4 / 100;
		    y = window_height / 12;
		    if (i != 5) {
			button_pos[button_map[6 * i + j].y].x = x;
			button_pos[button_map[6 * i + j].y].y = y;
			(void *) sprintf(button_number, "%d", button_map[6 * i + j].y);
			if (button_map[6 * i + j].y <= 9)
			    text_item.nchars = 1;
			else
			    text_item.nchars = 2;
			text_item.chars = button_number;
			text_item.delta = 0;
			text_item.font = (XID) NULL;
			XDrawText(display, win, gc, x + side / 3,
				  y + side / 3, text_item, 1);
			XDrawRectangle(display, win, gc, x, y, side, side);
			XFlush(display);
		    }
		    y += side + window_width * 4 / 100;
		}
	    } else {
		if (j == 5 && (i == 0 || i == 5)) {
		    /* no buttons in corners */
		    ;
		} else {
		    button_pos[button_map[6 * i + j].y].x = x;
		    button_pos[button_map[6 * i + j].y].y = y;
		    (void *) sprintf(button_number, "%d", button_map[6 * i + j].y);
		    if (button_map[6 * i + j].y <= 9)
			text_item.nchars = 1;
		    else
			text_item.nchars = 2;
		    text_item.chars = button_number;
		    text_item.delta = 0;
		    text_item.font = (XID) NULL;
		    XDrawText(display, win, gc, x + side / 3,
			      y + side / 3, text_item, 1);
		    XDrawRectangle(display, win, gc, x, y, side, side);
		    XFlush(display);
		}
		y += side + window_width * 4 / 100;
	    }
	}
    }
}


#include <varargs.h>

/*
    0 failed X call
    2 functional trace information
    3 low level library diagnostics
*/

/* VARARGS1 */
void
debug(va_alist) va_dcl
{
    va_list     ap;
    int         i;
    char       *format;

    va_start(ap);
    i = va_arg(ap, int);
    if (i > debug_level)
	return;
    format = va_arg(ap, char *);
    _doprnt(format, ap, stderr);
    va_end(ap);
}

/*    Draw the position indicator for the dial circle */
indicator(which, expose)
    int         which;
    int         expose;
{
    XPoint      ind[2];
    char        dial_number[4];
    XTextItem   text_item;


    if ((endpts[which].x != 0) && !expose) {
	ind[0] = centers[which];
	ind[1] = endpts[which];
	XSetForeground(display, gc, WhitePixel(display, screen));
	XDrawLines(display, dial_win, gc, ind, 2, CoordModeOrigin);
    }
    endpts[which].x = centers[which].x + (int) (sin(angles[which]) * dia);
    endpts[which].y = centers[which].y + (int) (cos(angles[which]) * dia);
    ind[0] = centers[which];
    ind[1] = endpts[which];
    XSetForeground(display, gc, BlackPixel(display, screen));
    XDrawLines(display, dial_win, gc, ind, 2, CoordModeOrigin);
    (void *) sprintf(dial_number, "%d", which);
    text_item.nchars = 1;
    text_item.chars = dial_number;
    text_item.delta = 0;
    text_item.font = (XID) NULL;
    XDrawText(display, dial_win, gc, centers[which].x - 10,
	      centers[which].y - 10, text_item, 1);
}

dofocus(device, win)
    XID         device;
    Window      win;
{
    int         i;

    i = XGetDeviceFocus(display, device, &focus_return,
			&revert_to_return, &focus_time_return);
    debug(3, "Get Device Focus returns %d\n", i);
    error_code = XSetDeviceFocus_code;
    expect = BadMatch;
    if (focus) {
	/* fix it for each device choice */
	i = XSetDeviceFocus(display, device, win,
			    revert_to_return, CurrentTime);
	debug(3, "Window Set Device Focus returns %d\n", i);
    }
    if (none) {
	i = XSetDeviceFocus(display, device, None,
			    revert_to_return, CurrentTime);
	debug(3, "None Set Device Focus returns %d\n", i);
    }
    if (followkey) {
	i = XSetDeviceFocus(display, device, FollowKeyboard,
			    revert_to_return, CurrentTime);
	debug(3, "FollowKeyboard Set Device Focus returns %d\n", i);
    }
    if (pointerroot) {
	if (lp_device)
	    XSelectExtensionEvent(display, RootWindow(display, screen), lp_codes
				  ,5);
	if (dial_device && button_device)
	    XSelectExtensionEvent(display, RootWindow(display, screen),
				  db_codes, 5);
	else if (dial_device)
	    XSelectExtensionEvent(display, RootWindow(display, screen),
				  db_codes, 3);
	else
	    XSelectExtensionEvent(display, RootWindow(display, screen),
				  db_codes, 4);
	i = XSetDeviceFocus(display, device, PointerRoot,
			    revert_to_return, CurrentTime);
	debug(3, "PointerRoot Set Device Focus returns %d\n", i);
    }
    expect = Success;
}


event_codes()
{

    if (lp_device) {
	debug(3, "Lightpen event codes\n");
	DeviceMotionNotify(lp_handle, motion_notify_type, lp_motion_notify_class);
	debug(3, "Motion notify type = %d Motion notify class = %d\n",
	      motion_notify_type, lp_motion_notify_class);
	DeviceButtonPress(lp_handle, button_press_type, lp_button_press_class);
	DeviceButtonRelease(lp_handle, button_release_type, lp_button_release_class);
	debug(3, "Button Press type = %d Button press class = %d\n",
	      button_press_type, lp_button_press_class);
	debug(3, "Button Release type = %d Button release class = %d\n",
	      button_release_type, lp_button_release_class);
	DeviceFocusIn(lp_handle, device_focusin_type, lp_device_focusin_class);
	DeviceFocusOut(lp_handle, device_focusout_type, lp_device_focusout_class);
	debug(3, "Device focusin type = %d Device focusin class = %d\n",
	      device_focusin_type, lp_device_focusin_class);
	debug(3, "Device focusout type = %d Device focusout class = %d\n",
	      device_focusout_type, lp_device_focusout_class);

    }
    if (dial_device) {
	debug(3, "SunDials event codes\n");
	DeviceMotionNotify(db_handle, motion_notify_type, db_motion_notify_class);
	debug(3, "Motion notify type = %d Motion notify class = %d\n",
	      motion_notify_type, db_motion_notify_class);
    }
    if (button_device) {
	debug(3, "SunButtons event codes\n");
	DeviceButtonPress(db_handle, button_press_type, db_button_press_class);
	DeviceButtonRelease(db_handle, button_release_type, db_button_release_class);
	debug(3, "Button Press type = %d Button press class = %d\n",
	      button_press_type, db_button_press_class);
	debug(3, "Button Release type = %d Button release class = %d\n",
	      button_release_type, db_button_release_class);
    }
    if (dial_device || button_device) {
	DeviceFocusIn(db_handle, device_focusin_type, db_device_focusin_class);
	DeviceFocusOut(db_handle, device_focusout_type, db_device_focusout_class);
	debug(3, "Device focusin type = %d Device focusin class = %d\n",
	      device_focusin_type, db_device_focusin_class);
	debug(3, "Device focusout type = %d Device focusout class = %d\n",
	      device_focusout_type, db_device_focusout_class);
    }
    /* Extension events setup */
    if (lp_device) {
	lp_codes[0] = lp_motion_notify_class;
	lp_codes[1] = lp_button_press_class;
	lp_codes[2] = lp_button_release_class;
	lp_codes[3] = lp_device_focusin_class;
	lp_codes[4] = lp_device_focusout_class;
    }
    if (dial_device && !button_device) {
	db_codes[0] = db_motion_notify_class;
	db_codes[1] = db_device_focusin_class;
	db_codes[2] = db_device_focusout_class;
    } else if (!dial_device) {
	db_codes[0] = db_button_press_class;
	db_codes[1] = db_button_release_class;
	db_codes[2] = db_device_focusin_class;
	db_codes[3] = db_device_focusout_class;
    } else {
	db_codes[0] = db_button_press_class;
	db_codes[1] = db_button_release_class;
	db_codes[2] = db_device_focusin_class;
	db_codes[3] = db_device_focusout_class;
	db_codes[4] = db_motion_notify_class;
    }

}

options(argc, argv)
    int         argc;
    char      **argv;
{
    char        testing[1024];
    long        strtol();
    char       *next;

    bzero(testing, 1024);
    bzero(title, 256);
    while ((o = getopt(argc, argv, "D:d:Gfg:knpt:v")) != -1) {
	switch (o) {
	case 'D':		/* devices to use */
	    strcat(testing, "Device(s) used: ");
	    if (index(optarg, 'l') != NULL) {
		lp_device++;
		strcat(testing, "lightpen ");
	    }
	    if (index(optarg, 'd') != NULL) {
		dial_device++;
		strcat(testing, "dials ");
	    }
	    if (index(optarg, 'b') != NULL) {
		button_device++;
		strcat(testing, "buttons ");
	    }
	    break;
	case 'G':		/* grab  device(s) */
	    grab++;
	    focus = followkey = none = pointerroot = 0;
	    strcat(testing, " grab window");
	    break;
	case 'd':		/* print out stream of conciousness messages */
	    debug_level = strtol(optarg, (char **) NULL, 10);;
	    break;
	case 'f':		/* focus to window */
	    focus++;
	    grab = followkey = none = pointerroot = 0;
	    strcat(testing, " focus window");
	    break;
	case 'g':		/* geometry (dont think it works) */
	    geom_x = strtol(optarg, &next, 10);
	    if (index(next, '+'))
		geom_y = strtol(next + 1, (char **) NULL, 10);
	    else
		geom_x = geom_y = 0;
	    break;
	case 'k':		/* focus is followkeyboard */
	    followkey++;
	    focus = grab = none = pointerroot = 0;
	    strcat(testing, " focus followkeyboard");
	    break;
	case 'n':		/* focus is none - no events get through */
	    none++;
	    focus = grab = followkey = pointerroot = 0;
	    strcat(testing, " focus none");
	    break;
	case 'p':		/* focus is pointerroot root window gets ext
				 * events */
	    pointerroot++;
	    focus = grab = followkey = none = 0;
	    strcat(testing, " focus pointerroot");
	    break;
	case 't':		/* window title */
	    strcat(title, optarg);
	    break;
	case 'v':		/* extremely verbose */
	    debug_level = 4;
	    break;
	default:
	    (void) fprintf(stderr, "usage: %s [-D d|b|l] [-d num] ", argv[0]);
	    (void) fprintf(stderr, "[-G] [-f] [-k] [-n] [-p] [-v]\n");
	    exit(1);
	}
    }
    if (!lp_device && !dial_device && !button_device) {
	dial_device++;
	strcat(testing, "Device used: dials ");
    }
    if (!focus && !grab && !followkey && !none && !pointerroot) {
	focus++;
	strcat(testing, " focus window");
    }
    fprintf(stderr, "%s\n", testing);
    fprintf(stderr, "Click inside any window to end test.\n");
}

extensions(dial_id, lp_id)
    XID        *dial_id,
               *lp_id;
{
    char      **answer;
    int         nextentions,
                ndevices;
    int         i;
    XDeviceInfo *xdevlist;

    answer = XListExtensions(display, &nextentions);
    debug(3, "Number of extentions %d\n", nextentions);

    /* Extensions */
    for (i = 0; i < nextentions; i++) {
	debug(3, " Extention %d [%s]\n", i, answer[i]);
	if (XQueryExtension(display, answer[i], &qmajor,
			    &qminor, &qfirsterror)) {
	    debug(3, " Major %d minor %d firsterror %d\n",
		  qmajor, qminor, qfirsterror);
	} else {
	    debug(0, "Extest: FAILED QueryExtension failed.\n");
	    exit(1);
	}
    }
    /* Input extension */
    xdevlist = XListInputDevices(display, &ndevices);
    debug(3, "Number of input devices %d\n", ndevices);

    {
	int         i,
	            j,
	            k;
	XAnyClassPtr classInfo;
	XKeyInfoPtr key;
	XButtonInfoPtr but;
	XValuatorInfoPtr val;

	for (i = 0; i < ndevices;
		i++) {
	    debug(3, "<%s> %d classes. Type %s\n", xdevlist[i].name,
	    xdevlist[i].num_classes, XGetAtomName(display, xdevlist[i].type));
	    classInfo = xdevlist[i].inputclassinfo;
	    for (j = 0; j <
		    xdevlist[i].num_classes; j++) {
		switch (classInfo->class) {
		case KeyClass:
		    key = (XKeyInfoPtr) classInfo;
		    debug(3, "  Key class min_key = %d max_key = %d numkeys = %d \n "
			  ,key->min_keycode, key->max_keycode, key->num_keys);
		    break;
		case ButtonClass:
		    but = (XButtonInfoPtr)
			classInfo;
		    if (!strcmp(xdevlist[i].name,
				"sundials"))
			*dial_id = xdevlist[i].id;
		    debug(3, "  Button class num_buttons = %d\n",
			  but->num_buttons);
		    break;
		case ValuatorClass:

		    val = (XValuatorInfoPtr) classInfo;
		    if (!strcmp(xdevlist[i].name,
				"sundials"))
			*dial_id = xdevlist[i].id;
		    if (!strcmp(xdevlist[i].name,
				"lightpen"))
			*lp_id = xdevlist[i].id;
		    debug(3, "  Valuator class num_axes = %d, mode = %d \n "
			  ,val->num_axes, val->mode);
		    debug(3, " motion_buffer = %d \n ", val->motion_buffer);
		    for (k = 0; k < val->num_axes; k++)
			debug(3, "     Axis[%d] resolution = %d min = %d max = %d \n "
			 ,k, val->axes[k].resolution, val->axes[k].min_value,
			      val->axes[k].max_value);
		    break;
		default:
		    debug(0, "Extest: FAILED XListDevices Unknown class %d\n",
			  xdevlist[i].inputclassinfo->class);
		    exit(1);
		    break;
		}
		classInfo = (XAnyClassPtr)
		    (((char *) classInfo) + classInfo->length);
	    }
	}
    }
    XFreeDeviceList(xdevlist);
}

window_properties(argc, argv)
    int         argc;
    char      **argv;
{
    int         x = 0,
                y = 0;
    XSetWindowAttributes attr;
    unsigned int border_width = 4;
    Pixmap      db_pixmap,
                lp_pixmap,
                cursor_pixmap,
                mask_pixmap;
    XSizeHints  size_hints;
    XWMHints    wm_hints;

    /* Window set up */
    screen = DefaultScreen(display);

    attr.border_pixel = BlackPixel(display, screen);
    attr.background_pixel = BlackPixel(display, screen);
    debug(2, "Create window\n");

    dial_win = XCreateSimpleWindow(display, RootWindow(display, screen),
				   geom_x ? geom_x : x, geom_y ? geom_y : y,
				   250, 400, border_width,
				   BlackPixel(display, screen),
				   WhitePixel(display, screen));
    button_win = XCreateSimpleWindow(display, RootWindow(display, screen),
				 geom_x ? geom_x : x + width, geom_y ? geom_y
				     : y,
				     450, 450, border_width,
				     BlackPixel(display, screen),
				     WhitePixel(display, screen));
    lp_win = XCreateSimpleWindow(display, RootWindow(display, screen),
				 geom_x ? geom_x : 0, geom_y ? geom_y : 0,
				 1100, 800, border_width,
				 BlackPixel(display, screen),
				 WhitePixel(display, screen));
    db_pixmap = XCreateBitmapFromData(display, dial_win, db_bitmap_bits,
				      icon_bitmap_width, icon_bitmap_height);
    lp_pixmap = XCreateBitmapFromData(display, lp_win, lp_bitmap_bits,
				      icon_bitmap_width, icon_bitmap_height);
    cursor_pixmap = XCreateBitmapFromData(display, lp_win, lp_cursor_bitmap,
					  16, 16);
    mask_pixmap = XCreateBitmapFromData(display, lp_win, lp_mask,
					16, 16);
    {
	XColor      white,
	            black,
	            notused;

	XLookupColor(display, DefaultColormap(display, screen), "black",
		     &notused, &black);
	XLookupColor(display, DefaultColormap(display, screen), "white",
		     &notused, &white);
	lp_cursor = XCreatePixmapCursor(display, cursor_pixmap, mask_pixmap, black,
					white, 0, 15);
    }

    size_hints.flags = PPosition | PSize | PMinSize;
    size_hints.x = x;
    size_hints.y = y;
    size_hints.width = width;
    size_hints.height = height;
    size_hints.min_width = 25;
    size_hints.min_height = 40;

    debug(2, "Standard properties\n");
    XSetStandardProperties(display, dial_win, title[0] ? title : "SunDials"
			   ,"Dials", db_pixmap, argv, argc, &size_hints);
    size_hints.x = x + width;
    size_hints.width = width2;
    size_hints.height = height2;
    XSetStandardProperties(display, button_win, title[0] ? title : "SunButtons", "Buttons",
			   db_pixmap, argv, argc, &size_hints);

    size_hints.x = 0;
    size_hints.width = width3;
    size_hints.height = height3;
    XSetStandardProperties(display, lp_win, title[0] ? title : "Lightpen", "Pen",
			   lp_pixmap, argv, argc, &size_hints);

    wm_hints.flags = StateHint | IconPixmapHint;
    wm_hints.icon_pixmap = lp_pixmap;
    wm_hints.initial_state = IconicState;

    XSetWMHints(display, lp_win, wm_hints);
}

prep_for_events()
{
    int         event_count;

    debug(2, "Map window\n");
    if (lp_device) {
	XSelectInput(display, lp_win, 0xffffff);
	XSelectExtensionEvent(display, lp_win, lp_codes, 5);
	XMapWindow(display, lp_win);
	if (grab)
	    XGrabDevice(display, lp_handle, lp_win, 1, 5, lp_codes,
			GrabModeSync, GrabModeSync, CurrentTime);
    }
    if (dial_device && button_device)
	event_count = 5;
    else if (dial_device)
	event_count = 3;
    else
	event_count = 4;
    if (dial_device) {
	XSelectInput(display, dial_win, 0xffffff & ~KeymapStateMask);
	XSelectExtensionEvent(display, dial_win, db_codes, event_count);
	XMapWindow(display, dial_win);
	if (grab)
	    XGrabDevice(display, db_handle, dial_win, 1, event_count, db_codes,
			GrabModeSync, GrabModeSync, CurrentTime);
    }
    if (button_device) {
	XSelectInput(display, button_win, 0xffffff & ~KeymapStateMask);
	XSelectExtensionEvent(display, button_win, db_codes, event_count);
	XMapWindow(display, button_win);
	if (grab)
	    XGrabDevice(display, db_handle, button_win, 1, event_count, db_codes,
			GrabModeSync, GrabModeSync, CurrentTime);
    }
    gc = DefaultGC(display, screen);
    CheckExtInit(display, XInput_Initial_Release);
}

button_report(buttonEvent)
    XDeviceButtonEvent *buttonEvent;
{
    if (pointerroot)
	fprintf(stderr, "Button %s Event deviceid = %d\n",
		buttonEvent->type == button_press_type ?
		"Pressed" : "Released", buttonEvent->deviceid);
    debug(2, "Button %s Event deviceid = %d\n",
	  buttonEvent->type == button_press_type ?
	  "Pressed" : "Released", buttonEvent->deviceid);
    debug(3, "   serial=%d  send_event=%d  time=%d\n",
	  buttonEvent->serial, buttonEvent->send_event,
	  buttonEvent->time);
    debug(3, "   x=%d   y=%d  xroot=%d  yroot=%d same_screen %= d \n ",
	  buttonEvent->x, buttonEvent->y,
	  buttonEvent->x_root,
	  buttonEvent->y_root, buttonEvent->same_screen);
    debug(3, "   state=%x   button=%x %d\n",
	  buttonEvent->state, buttonEvent->button,
	  buttonEvent->button);
    debug(3, "   axes_count=%d  first_axis=%d\n",
	  buttonEvent->axes_count, buttonEvent->first_axis);
}

motion_report(motionEvent)
    XDeviceMotionEvent *motionEvent;
{
    if (debug_level > 20)
	return;
    if (debug_level > 3)
	debug_level++;
    if (pointerroot)
	fprintf(stderr, "Motion Notify Event deviceid = %d\n",
		motionEvent->deviceid);
    debug(2, "Motion Notify Event deviceid = %d\n",
	  motionEvent->deviceid);
    debug(3, "   serial=%d  send_event=%d  time=%d\n",
	  motionEvent->serial, motionEvent->send_event,
	  motionEvent->time);
    debug(3, "   x=%d   y=%d  xroot=%d  yroot=%d\n",
	  motionEvent->x, motionEvent->y, motionEvent->x_root,
	  motionEvent->y_root);
    debug(3, "   state=%d   is_hint=%d  same_screen=%d\n",
	  motionEvent->state, motionEvent->is_hint,
	  motionEvent->same_screen);
    debug(3, "   axes_count=%d  first_axis=%d\n",
	  motionEvent->axes_count, motionEvent->first_axis);
}

/*
 * This function handles X errors.
 */

int         Dflag = 1;

handle_x_errors(disp, error)
    Display    *disp;
    XErrorEvent *error;
{
    char        buf[256];

    if (error->request_code == qmajor &&
	    error->minor_code == error_code &&
	    error->error_code == expect)
	if (error->error_code >= qfirsterror &&
		error->error_code <= qfirsterror + 4) {
	    XUndefineCursor(display, PointerRoot, lp_cursor);
	    if (Dflag)
		printf("%s returned %s correctly.\n",
		       extfuncs[error->minor_code],
		       ext_errors[error->error_code - qfirsterror]);
	    return;
	} else {
	    XUndefineCursor(display, PointerRoot, lp_cursor);
	    if (Dflag)
		printf("%s returned %s correctly.\n",
		       extfuncs[error->minor_code],
		       std_errors[error->error_code]);
	    return;
	}
    /* gstatus = -1; */
    if (error->request_code == qmajor)
	printf("    Minor code=%s.\n", extfuncs[error->minor_code]);
    else
	printf("    Minor code=%d.\n", error->minor_code);

    if (error->error_code >= Success &&
	    error->error_code <= BadImplementation)
	printf("    Error code=%s.\n", std_errors[error->error_code]);
    else if (error->error_code >= qfirsterror &&
	     error->error_code <= qfirsterror + 4)
	printf("    Error code=%s.\n", ext_errors[error->error_code - qfirsterror]);
    else
	printf("    Error code=%d.\n", error->error_code);
    printf("    Resource id=%d.\n", error->resourceid);
    return (0);
}
