/*
 * tvtime channel changer
 * 2003/12/27
 */

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

static const char *command = "tvtime-command";
static int joy_fd = 0;
static char buf[256];
static int channelNum[12] = {12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

static void execCommand(const char *str)
{
	printf("%s\n", buf);
	system(str);
}

static void sendChannelNum(int num)
{
	if(num > 9) {
		snprintf(buf, 256, "%s CHANNEL_%d CHANNEL_%d ENTER", command, num/10, num%10);
	} else {
		snprintf(buf, 256, "%s CHANNEL_%d ENTER", command, num);
	}
	execCommand(buf);
}

static void main_loop()
{
	struct js_event event;
	int ret;

	for(;;) {
		ret = read(joy_fd, &event, sizeof(struct js_event));
		if(ret != sizeof(event)) {
			continue;
		}
		switch(event.type) {
			case JS_EVENT_BUTTON:
				if(event.value == 1) {
					sendChannelNum(channelNum[event.number]);
				}
				break;
			default:
				break;
		}
	}
}

int main(int argc, char **argv)
{
	char *str;

	if(argc < 2) {
		str = "/dev/input/js0";
	} else {
		str = argv[1];
	}

	joy_fd = open(str, O_RDONLY);
	if(joy_fd < 0) {
		perror("Failed to open device: ");
		exit(1);
	}
	main_loop();

	return 0;
}

