/********************************************************
*
* joystick.c	joystick input module for r4d
*
* Author:	Gary Hoggard	2 May 1998
*
********************************************************/

#include "r4.h"

main()
	{
	unsigned int switches, x, y;
	char lib[128];			/* pathname of library dir */
	char pipe[128];			/* pathname of named pipe */
	FILE *PIPE;			/* file pointer for named pipe */
	char move;			/* byte indicating movement direction */

	if (getenv("DEBUG"))
		{
		debug=YES;
		dlog = fopen(DEBUGFILE, "a");
		}

	/* open the named pipe for writing */
	if (getenv("R4_LIB"))
		strcpy(lib, getenv("R4_LIB"));
	else
		strcpy(lib, LIB);
	sprintf(pipe, "%s/joystick_pipe", lib);
	if ((PIPE = fopen(pipe, "w")) == NULL)
		{
		perror(pipe);
		exit(1);
		}
	portinit();

	while (YES)
		{
		/*if (! (joystick_on(lib) && is_joystick(1)))*/
		if (! is_joystick(1))
			{
			sleep(1);
			continue;
			}
		/* get joystick switches and position */
		switches = gameport(&x, &y, 1);
		if (switches)
			{
			fprintf(PIPE, "j%d\n", switches);
			fflush(PIPE);
			}
		if (x == 0 && y == 0)		move = '1';	/* left fwd */
		else if (x > 1 && y == 0)	move = '2';	/* right fwd */
		else if (x == 0 && y > 1)	move = '3';	/* left rev */
		else if (x > 1 && y > 1)	move = '4';	/* right rev */
		else if (x == 0 && y > 0)	move = 'l';	/* left spin */
		else if (x > 1 && y > 0)	move = 'r';	/* right spin */
		else if (x > 0 && y == 0)	move = 'f';	/* forward */
		else if (x > 0 && y > 1)	move = 'b';	/* reverse */
		else move = '0';				/* stop */

		fprintf(PIPE, "m%c\n", move);
		fflush(PIPE);
		portout(0, 0, 100, NO);				/* 100ms pause */
		}
	}

joystick_on(char *lib)
	{
	/*
	* test if $R4_LIB/enable_joystick exists
	*/
	char filename[128];
	int fp, exists;

	sprintf(filename, "%s/enable_joystick", lib);
	if ((fp = open(filename, O_RDONLY)) > 0)
		{
		close(fp);
		exists = YES;
		}
	else
		exists = NO;
	return(exists);
	}

/*______________________end_of_joystick.c__________________*/

