Ultimate PC game controller/mouse

I am working on an ultimate controller for Colobot, but some things have to either be done by mouse, or keyboard. Using the slider I switch between the two. The thing is, when I turn on the mouse control, the keyboard control keeps running at the same time. could you please fix my code?

Code :

#include <Esplora.h>

boolean buttonStates[8];

const byte buttons = {
JOYSTICK_DOWN,
JOYSTICK_LEFT,
JOYSTICK_UP,
JOYSTICK_RIGHT,
SWITCH_4,
SWITCH_2,
SWITCH_3,
SWITCH_1,
};

const char keystrokes = {
KEY_DOWN_ARROW,
KEY_LEFT_ARROW,
KEY_UP_ARROW,
KEY_RIGHT_ARROW,
‘E’,RFRFRFRRRRRRRFEE
KEY_ESC,
‘R’,
‘F’
};

void setup() {
Keyboard.begin();
Mouse.begin();
}

void loop() {

int S = Esplora.readSlider();

for (byte thisButton = 0; thisButton < 8; thisButton++) {
boolean lastState = buttonStates[thisButton];
boolean newState = Esplora.readButton(buttons[thisButton]);
if (lastState != newState) { // Something changed!

if (newState == PRESSED) {
Keyboard.press(keystrokes[thisButton]);
}
else if (newState == RELEASED) {
Keyboard.release(keystrokes[thisButton]);
}
}

// Store the new button state, so you can sense a difference later:
buttonStates[thisButton] = newState;
}

delay(50);

if (S > 100) {

int oldScrollUp = 0;
int oldScrollDown = 0;
int stateTime = 0;

#define THRESHOLD 20

int xValue = Esplora.readJoystickX();
int yValue = Esplora.readJoystickY();

int leftButton = Esplora.readJoystickSwitch() && Esplora.readButton(SWITCH_LEFT);
int rightButton = Esplora.readButton(SWITCH_RIGHT);

int scrollUp = Esplora.readButton(SWITCH_UP);
int scrollDown = Esplora.readButton(SWITCH_DOWN);

int range = Esplora.readSlider();

int mouseRange = map(range, 0, 1023, 2, 10);
int mouseX = (xValue < THRESHOLD && xValue > -THRESHOLD) ? 0 : map(xValue, -512, 512, mouseRange, -mouseRange);
int mouseY = (yValue < THRESHOLD && yValue > -THRESHOLD) ? 0 : map(yValue, -512, 512, -mouseRange, mouseRange);
int wheel = 0;
if (oldScrollUp != scrollUp || oldScrollDown != scrollDown)
{
wheel = (scrollUp != scrollDown) ? (scrollUp ? -mouseRange : mouseRange) : 0;
oldScrollUp = scrollUp;
oldScrollDown = scrollDown;
stateTime = millis();
}
else if ((millis() - stateTime) % 100 == 0 && (millis() - stateTime) >= 1000)
{
wheel = (scrollUp != scrollDown) ? (scrollUp ? -mouseRange : mouseRange) : 0;
}
Mouse.move(mouseX, mouseY, wheel);

if (!leftButton)
Mouse.press(MOUSE_LEFT);
else
Mouse.release(MOUSE_LEFT);

if (!rightButton)
Mouse.press(MOUSE_RIGHT);
else
Mouse.release(MOUSE_RIGHT);

}
}

You’ll have to poll (read) the slide often.
If (it’s < threshold)
{ it branches to mouse stuff }
else
{ it’s left to keyboard stuff }