/************************************************************
* Copyright (C) 2007-2008 Masahiko SAWAI All Rights Reserved. 
************************************************************/

#include <stdio.h>
#include <stdlib.h>

#include <wiiremote.h>

static int done;

int main(int argc, char *argv[])
{
	int number, i;
	WRMT_WiiRemote *wiiremotes[WRMT_MAX_DEVICES];
	
	if (WRMT_Init() != 0)
	{
		fprintf(stderr, "WRMT_Init() Faild.\n");
		exit(-1);
	}
	atexit(WRMT_Quit);

	number = WRMT_GetNumWiiRemote();
	fprintf(stderr, "Number of Wii Remote : %d\n", number);
	if (number <= 0)
	{
		fprintf(stderr, "No Wii Remote Found.\n");
		exit(-1);
	}

	for (i = 0;i < number;i++)
	{
		WRMT_IOReturn rc;

		wiiremotes[i] = WRMT_GetWiiRemoteAt(i);
		rc = WRMT_WiiRemote_Open(wiiremotes[i]);
		if (rc == WRMT_IO_ERROR)
		{
			fprintf(stderr, "WRMT_WiiRemote_Open(%d) Fail.\n", i);
			fprintf(stderr, "\t%s\n", WRMT_GetError());
			exit(-1);
		}
		fprintf(stderr, "[%d] WRMT_WiiRemote_Open() Success.\n", i);

		WRMT_WiiRemote_SetEnabled(wiiremotes[i], WRMT_FUNCTION_CONTINUOUS, 0);
		WRMT_WiiRemote_SetEnabled(wiiremotes[i], WRMT_FUNCTION_MOTION, 0);
		WRMT_WiiRemote_SetEnabled(wiiremotes[i], WRMT_FUNCTION_IR, 0);
	}

	done = 0;
	while (!done)
	{
		int updated_index;

		while ((updated_index = WRMT_Poll()) >= 0)
		{
			int button_state;

			button_state = WRMT_WiiRemote_GetState(wiiremotes[updated_index], WRMT_DATA_BUTTONS);
			fprintf(stderr, "[%d] : 2:%d, 1:%d, B:%d, A:%d, -:%d, H:%d, L:%d, R:%d, D:%d, U:%d, +:%d\n",
				updated_index,
				((button_state & WRMT_MASK_BUTTON_TWO) != 0),
				((button_state & WRMT_MASK_BUTTON_ONE) != 0),
				((button_state & WRMT_MASK_BUTTON_B) != 0),
				((button_state & WRMT_MASK_BUTTON_A) != 0),
				((button_state & WRMT_MASK_BUTTON_MINUS) != 0),
				((button_state & WRMT_MASK_BUTTON_HOME) != 0),
				((button_state & WRMT_MASK_BUTTON_LEFT) != 0),
				((button_state & WRMT_MASK_BUTTON_RIGHT) != 0),
				((button_state & WRMT_MASK_BUTTON_DOWN) != 0),
				((button_state & WRMT_MASK_BUTTON_UP) != 0),
				((button_state & WRMT_MASK_BUTTON_PLUS) != 0)
			);

			if (button_state & WRMT_MASK_BUTTON_HOME) done = 1;
		}

		fflush(stderr);
		WRMT_Sleep(30);
	}

	fprintf(stderr, "\n");
	for (i = WRMT_GetNumWiiRemote()-1;i >= 0;i--)
	{
		fprintf(stderr, "WRMT_WiiRemote_Close(%d).\n", i);
		WRMT_WiiRemote_Close(wiiremotes[i]);
	}
	fprintf(stderr, "WRMT_Quit().\n");

	return 0;
}
