/*
	joypad.c	check your joypad buttons in scripts

	by Daniel Balster.  Example usage:
	
	joypad blue
	if warn
	  echo "blue pressed"
	endif
	
	joypad fwd rew
	if warn
	  echo "forward&rewind pressed"
	endif
	
	joypad play	; this could be in your s:startup-sequence ?
	if warn
	  cd GAMES:
	  GamesMenu
	endif
	
	joypad red green
	if warn
	  GFX:3D-View
	endif

	(not much comments in it - forgive me)
*/

#include <exec/exec.h>
#include <dos/dos.h>
#include <libraries/lowlevel.h>
#include <devices/cd.h>
#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/lowlevel.h>

#define TEMPLATE "RED/S,BLUE/S,YELLOW/S,GREEN/S,FWD/S,REW/S,PLAY/S,PORT/N,QUIET/S"

#define BUTTON_MASK (JPF_BUTTON_RED|JPF_BUTTON_BLUE|JPF_BUTTON_GREEN|JPF_BUTTON_YELLOW \
	|JPF_BUTTON_FORWARD|JPF_BUTTON_REVERSE|JPF_BUTTON_PLAY)			

struct abc {
	ULONG	red,blue,yellow,green,fwd,rew,play;
	ULONG	port;
	ULONG	quiet;
	ULONG	pads[7]; /* someone said RDArgs must be sized to a 16-longs boundary ??? */
};

int main (void)
{
	struct RDArgs *rdargs;
	struct abc args = {0};
	ULONG bits, port=1, mymask;
	ULONG check = RETURN_OK;

	if (rdargs=ReadArgs(TEMPLATE,(LONG*)&(args),NULL))
	{
		if(!args.quiet)
			PutStr("*** JoyPad Version 1.0.0 *** by Daniel Balster\n");

			if (args.port) port = *(ULONG*)args.port;

			bits = ReadJoyPort (port);
			
			if ((bits & JP_TYPE_MASK)==JP_TYPE_NOTAVAIL)
				PutStr ("port not available\n");
			if ((bits & JP_TYPE_MASK)==JP_TYPE_UNKNOWN)
				PutStr ("controller type unknown\n");
			
			mymask = 0x00000000;
			
			/* create a bit-set comparison mask */
			
			if (args.red) mymask |= JPF_BUTTON_RED;
			if (args.blue) mymask |= JPF_BUTTON_BLUE;
			if (args.green) mymask |= JPF_BUTTON_GREEN;
			if (args.yellow) mymask |= JPF_BUTTON_YELLOW;
			if (args.fwd) mymask |= JPF_BUTTON_FORWARD;
			if (args.rew) mymask |= JPF_BUTTON_REVERSE;
			if (args.play) mymask |= JPF_BUTTON_PLAY;
			
			/* compare two sets */
			
			if ((bits&BUTTON_MASK) == mymask) check=RETURN_WARN;

			if (check && !args.quiet) PutStr ("button combination pressed!\n");

		FreeArgs(rdargs);
	}
	else PrintFault(IoErr(),0);

	return check;
}
