/*
 * Fvwm Virtual Desktop Changer 2
 * 2003/11/28
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/joystick.h>

static int joy1_fd = 0;
static int joy2_fd = 0;
static char buf[256];
static int lastX = 0;
static int lastY = 0;

void movePage(int x, int y)
{
	printf("%d, %d\n", x, y);
	snprintf(buf, 256, "FvwmCommand 'GotoPage %d %d'", x, y);
	system(buf);
}

void readJoy(int fd, int *val)
{
	struct js_event event;
	int ret;

	ret = read(fd, &event, sizeof(struct js_event));
	if(ret != sizeof(event)) {
		return;
	}
	switch(event.type) {
		case JS_EVENT_BUTTON:
			if(event.value == 1) {
				*val = event.number;
			}
			break;
		default:
			break;
	}
}

void main_loop()
{
	fd_set fdset;
	int maxfd;
	int ret;

	if(joy1_fd > joy2_fd) {
		maxfd = joy1_fd;
	} else {
		maxfd = joy2_fd;
	}
	maxfd++;

	for(;;) {
		FD_ZERO(&fdset);
		FD_SET(joy1_fd, &fdset);
		FD_SET(joy2_fd, &fdset);
		ret = select(maxfd, &fdset, NULL, NULL, NULL);

		if(ret == -1) {
			perror("select()");
		} else {
			if(FD_ISSET(joy1_fd, &fdset)) {
				readJoy(joy1_fd, &lastX);
			}
			if(FD_ISSET(joy2_fd, &fdset)) {
				readJoy(joy2_fd, &lastY);
			}
			movePage(lastX, lastY);
		}
	}
}

int main(int argc, char **argv)
{
	char *str1, *str2;

	if(argc != 3) {
		str1 = "/dev/input/js0";
		str2 = "/dev/input/js1";
	} else {
		str1 = argv[1];
		str2 = argv[2];
	}

	joy1_fd = open(str1, O_RDONLY);
	if(joy1_fd < 0) {
		perror("Failed to open device: ");
		exit(1);
	}
	joy2_fd = open(str2, O_RDONLY);
	if(joy2_fd < 0) {
		perror("Failed to open device: ");
		exit(1);
	}

	main_loop();

	return 0;
}

