/* 
 * Project: SDL
 * Demo Code
 * This demo simply inits the library.
 *
 * Joseph M. Robertson, jmr, jmrobert5@home.com
 *
 * Copyright(c) 2001, Joseph M. Robertson.
 * This code protected by the GNU Public License.
 * See the LICENSE file or http://www.gnu.org for details.
 */

/*
 * build code
 * gcc -c init.c -I/usr/include/SDL
 * gcc -o init init.o -lSDL -lpthread
 */

#include "SDL.h"   /* All SDL App's need this */
#include <stdio.h>

int main() {
     int i=0;
     SDL_Joystick *joystick;     
     SDL_Event event;
     int number_of_buttons;

     printf("Initializing SDL.\n");   
     /* Initialize defaults, Video and Audio */
     if((SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK)==-1)) {
	  printf("Could not initialize SDL: %s.\n", SDL_GetError());
	  exit(-1);
     }     
     printf("SDL initialized.\n");

     /* query the joystick */
     /* if this doesn't work make sure 
      * 1.  the /dev/js* exists
      * 2.  the modules joydev.o, ns588.o and the device driver is loaded
      */
     printf("%i joysticks were found.\n\n", SDL_NumJoysticks() );
     printf("The names of the joysticks are:\n");
     for( i=0; i < SDL_NumJoysticks(); i++ )
     {
	  printf("    %s\n", SDL_JoystickName(i));
     }
     
     /* set up a real joystick devioce */
     SDL_JoystickEventState(SDL_ENABLE);
     joystick = SDL_JoystickOpen(0);

     number_of_buttons = SDL_JoystickNumButtons(joystick);
     printf("%i buttons were detected.\n", number_of_buttons);

     while(1){
	  /* Other initializtion code goes here */       
	  /* Start main game loop here */     
	  while(SDL_PollEvent(&event))
	  { 
	       switch(event.type)
	       { 
	       case SDL_KEYDOWN:
		    /* handle keyboard stuff here */
		    break;             
	       case SDL_QUIT:
		    /* Set whatever flags are necessary to */
		    /* end the main game loop here */
		    SDL_JoystickClose(joystick);

		    printf("Quitting SDL.\n");
   
		    /* Shutdown all subsystems */
		    SDL_Quit();

		    printf("Quitting....\n");     
		    exit(0);
     
		    break;
	       case SDL_JOYAXISMOTION:  /* Handle Joystick Motion */
		    if ( ( event.jaxis.value < -3200 ) || (event.jaxis.value > 3200 ) ) {
			 if( event.jaxis.axis == 0) {
			      /* Left-right movement code goes here */
			      printf("Left-Right event.jaxis.value: %i\n", event.jaxis.value);
			 }         
			 if( event.jaxis.axis == 1) {
			      /* Up-Down movement code goes here */
			      printf("Up-Down event.jaxis.value: %i\n", event.jaxis.value);
			 }
		    }
		    break;
	       case SDL_JOYBUTTONDOWN:  /* Handle Joystick Button Presses */
		    if ( event.jbutton.button == 0 ) {
			 /* code goes here */
		    }
		    printf("button number: %i pressed.\n", event.jbutton.button);
		    break;

	       }
	  }     /* End loop here */

     }
     
}

