#include <exec/types.h>
#include <exec/devices.h>
#include <graphics/gfx.h>
#include <devices/gameport.h>
#include <devices/inputevent.h>
#include <intuition/intuition.h>

extern int debug;

struct InputEvent gameEvent;
struct MsgPort *gameMsgPort;
struct IOStdReq *gameIOMsg;
int ControllerType;
int GameportOpen;
int gameIOPending;

trash_joy()
{
	if(gameIOPending &&
		!CheckIO(gameIOMsg)) AbortIO(gameIOMsg);
	if(ControllerType != GPCT_NOCONTROLLER)
		SetControllerType(GPCT_NOCONTROLLER);
	if(GameportOpen) CloseDevice(gameIOMsg);
	if(gameIOMsg) DeleteStdIO(gameIOMsg);
	if(gameMsgPort) DeletePort(gameMsgPort);
}

init_joy()
{
	gameIOMsg = 0;
	gameMsgPort = 0;
	ControllerType = GPCT_NOCONTROLLER;
	GameportOpen = 0;
	gameIOPending = 0;
	add_cleanup(trash_joy, "joystick");
	if(!(gameMsgPort = CreatePort(0, 0))) {
		printf("Can't create joystick port\n");
		cleanup(debug);
		exit(20);
	}
	if(!(gameIOMsg = CreateStdIO(gameMsgPort))) {
		printf("Can't create joystick message.\n");
		cleanup(debug);
		exit(20);
	}
	if(OpenDevice("gameport.device", 1, gameIOMsg, 0) != 0) {
		printf("Can't open gameport.device.\n");
		cleanup(debug);
		exit(20);
	}
	GameportOpen = 1;
	if(SetControllerType(GPCT_ABSJOYSTICK) != 0) {
		printf("Can't set controller type.\n");
		cleanup(debug);
		exit(20);
	}
	ControllerType = GPCT_ABSJOYSTICK;
	if(SetControllerTrigger() != 0) {
		printf("Can't set controller trigger.\n");
		cleanup(debug);
		exit(20);
	}
	SendGameIO();
}

SendGameIO()
{
	gameIOMsg->io_Command = GPD_READEVENT;
	gameIOMsg->io_Data = (APTR)&gameEvent;
	gameIOMsg->io_Length = sizeof(gameEvent);
	gameIOMsg->io_Flags = 0;

	SendIO(gameIOMsg);
	gameIOPending = 1;
}

SetControllerType(type)
SHORT type;
{
	BYTE buffer[1];
	gameIOMsg->io_Command = GPD_SETCTYPE;
	gameIOMsg->io_Length = 1;
	gameIOMsg->io_Data = (APTR)buffer;
	buffer[0] = type;
	SendIO(gameIOMsg);
	WaitPort(gameMsgPort);
	GetMsg(gameMsgPort);
	return (int)gameIOMsg->io_Error;
}

SetControllerTrigger()
{
	struct GamePortTrigger gpt;
	gameIOMsg->io_Command = GPD_SETTRIGGER;
	gameIOMsg->io_Length = sizeof(gpt);
	gameIOMsg->io_Data = (APTR)&gpt;
	gpt.gpt_Keys = GPTF_UPKEYS|GPTF_DOWNKEYS;
	gpt.gpt_Timeout = 0;
	gpt.gpt_XDelta = 1;
	gpt.gpt_YDelta = 1;

	return DoIO(gameIOMsg);
}


