#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>
#include <dev/wscons/wsconsio.h>

#define CLIP(v, l) do { if (v > l) v = l; if (v < -l) v = -l;} while (0)

main()
{
	int fd, nread;
	unsigned int type;
	struct wscons_event ev;
	int x, y, z, b0, b1, b2, b3, btn;

	x = y = z = b0 = b1 = b2 = b3 = btn = 0;

	fd = open("/dev/wsmouse0", 2);
	if (fd < 0) {
		perror("/dev/wsmouse0");
		exit(1);
	}

	fprintf(stderr, "   X    Y    Z   B0   B1   B2   B3  btn\n");
	while ((nread = read(fd, &ev, sizeof(ev))) > 0) {
		switch (ev.type) {
		case WSCONS_EVENT_MOUSE_DOWN:
			btn = ev.value;
			if (btn == 0)
				b0 = 1;
			else if (btn == 1)
				b1 = 1;
			else if (btn == 2)
				b2 = 1;
			else if (btn == 3)
				b3 = 1;
			break;
		case WSCONS_EVENT_MOUSE_UP:
			btn = ev.value;
			if (btn == 0)
				b0 = 0;
			else if (btn == 1)
				b1 = 0;
			else if (btn == 2)
				b2 = 0;
			else if (btn == 3)
				b3 = 0;
			break;
		case WSCONS_EVENT_MOUSE_DELTA_X:
			x += ev.value;
			break;
		case WSCONS_EVENT_MOUSE_DELTA_Y:
			y += ev.value;
			break;
		case WSCONS_EVENT_MOUSE_DELTA_Z:
			z += ev.value;
			break;
		case WSCONS_EVENT_MOUSE_ABSOLUTE_X:
			x = ev.value;
			break;
		case WSCONS_EVENT_MOUSE_ABSOLUTE_Y:
			y = ev.value;
			break;
		case WSCONS_EVENT_MOUSE_ABSOLUTE_Z:
			z = ev.value;
			break;
		default:
			break;
		}
		CLIP(x, 999);
		CLIP(y, 999);
		CLIP(z, 999);
		fprintf(stderr, "%4d %4d %4d  %s  %s  %s  %s   %d\r",
		    x, y, z,
		    b0 ? " ON" : "OFF",
		    b1 ? " ON" : "OFF",
		    b2 ? " ON" : "OFF",
		    b3 ? " ON" : "OFF",
		    btn);
	}
	if (nread < 0) 
		perror("read");
	exit(0);
}

