'
' NeoLib - Joystick Module
'
' Features:
'  2 subs
'  1 functions
' For a total of: 3 routines
'
' Specially designed and coded for AAP's QBCPC
' Official Library of the QuickBASIC Caliber Programming Compo (Summer & Autumn 2003)
'
' Special Thanks to the AAP Gamepad Library for QuickBASIC!
' Credits go to Adigun Azikiwe Polack
'

DECLARE FUNCTION neoJoyDetected% ()

DECLARE SUB neoJoyXY (X AS INTEGER, Y AS INTEGER)
DECLARE SUB neoJoyButton (ButtonA AS INTEGER, ButtonB AS INTEGER, ButtonC AS INTEGER, ButtonD AS INTEGER)

DEFINT A-Z
'$DYNAMIC


'/////////////////////////////////////////////////////////////////////////////
' FUNCTIONS
'/////////////////////////////////////////////////////////////////////////////
FUNCTION neoJoyDetected
	'detects the joystick and returns:
	' -1 : joystick found and usable
	'  0 : joystick not found

	'we use the standard QB STICK function here
	'because fortunately STICK(1) returns 1 (<2) when
	'not found or >1 when found

	IF STICK(1) < 2 THEN neoJoyDetected = 0 ELSE neoJoyDetected = -1
END FUNCTION

'/////////////////////////////////////////////////////////////////////////////
' SUBS
'/////////////////////////////////////////////////////////////////////////////
SUB neoJoyXY (X AS INTEGER, Y AS INTEGER)
	'gets the current x and y coordinates from the joystick
	'- X: where the X coordinate is stored in (0-199)
	'- Y: where the Y coordinate is stored in (0-199)

        'we first have to reset the joystick (so we can read values)
        OUT &H201, 0

        'now we have to make a loop, because this joystick port reads stupid
        'because if we have to read n times if either X or Y is n.
        CurrentX = 0
        CurrentY = 0
        DO
        	JoyInput = INP(&H201)
        	CurrentX = CurrentX + (JoyInput AND 1)
        	CurrentY = CurrentY + ABS((JoyInput AND 2) = 2)
        LOOP UNTIL (JoyInput AND 1) = 0 AND (JoyInput AND 2) = 0

        'now pass the values back
        X = CurrentX
        Y = CurrentY
END SUB

SUB neoJoyButton (ButtonA AS INTEGER, ButtonB AS INTEGER, ButtonC AS INTEGER, ButtonD AS INTEGER)
	'gets the button statuses of the joystick
	'- ButtonA: button A status is stored in here
	'- ButtonB: button B status is stored in here
	'- ButtonC: button C status is stored in here
	'- ButtonD: button D status is stored in here

        'we have to read the joystick port
        JoyData = INP(&H201)

        'bits: 7 6 5 4 3 2 1 0
        '      | | | |
        '      | | | \- Button A data
        '      | | \- Button B data
        '      | \- Button C data
        '      \- Button D data
        'Bit off: Button being Pressed
        'Bit on: Button is released

        'So we get:
        ButtonA = ((JoyData AND &H10) = 0)
        ButtonB = ((JoyData AND &H20) = 0)
        ButtonC = ((JoyData AND &H40) = 0)
        ButtonD = ((JoyData AND &H80) = 0)
END SUB
