 
 LinFrame frame = LinFrame();
 
-unsigned long currentMillis, lastHeartbeat, lastBackDown, lastEnterDown, lastMouseDown, lastOffDown, lastRtiWrite, lastPrevDown, lastNextDown, lastOnTrigger;
+unsigned long currentMillis, lastHeartbeat, lastRtiWrite, lastOnTrigger, buttonDownAt, lastButtonAt;
 int mouseSpeed = MOUSE_BASE_SPEED;
 short state = STATE_OFF;
+byte currentButton, currentJoystickButton;
 
 void setup() {
   pinMode(RX_LED, OUTPUT);

      break;
    case JOYSTICK_RIGHT:
      move_mouse(1, 0);
      break;
  }
}

void handle_buttons() {
  switch (frame.get_byte(2)) {
    case BUTTON_BACK:
      if (!lastBackDown)
        Consumer.press(HID_CONSUMER_AC_BACK);

      lastBackDown = currentMillis;

      if (!lastOffDown)
        lastOffDown = currentMillis;
      break;

    case BUTTON_ENTER:
      if (!lastEnterDown && state == STATE_ON)
        Mouse.press();

      lastEnterDown = currentMillis;
      break;

    case BUTTON_PREV:
      if (!lastPrevDown) {
        Consumer.write(MEDIA_PREVIOUS);
        debug("PREV");
      }

      lastPrevDown = currentMillis;
      break;

    case BUTTON_NEXT:
      if (!lastNextDown) {
        Consumer.write(MEDIA_NEXT);
        debug("NEXT");
      }
        
      lastNextDown = currentMillis;
      break;

    default:
      Serial.write(frame.get_byte(2));
      debug("");
      lastOffDown = 0;
  }
}

void move_mouse(int dx, int dy) {
  Mouse.move(dx * mouseSpeed, dy * mouseSpeed, 0);
  lastMouseDown = currentMillis;
  mouseSpeed += MOUSE_SPEEDUP;
}

void release_keys() {
  if (lastEnterDown && currentMillis - lastEnterDown > CLICK_TIMEOUT) {
    if (state == STATE_ON)
      Mouse.release();
    else
      turn_on();

    lastEnterDown = 0;
  }

  if (lastBackDown && currentMillis - lastBackDown > CLICK_TIMEOUT) {
    Consumer.release(HID_CONSUMER_AC_BACK);
    lastBackDown = 0;
  }

  if (lastMouseDown && currentMillis - lastMouseDown > CLICK_TIMEOUT) {
    lastMouseDown = 0;
    mouseSpeed = MOUSE_BASE_SPEED;
  }

  if (lastOffDown && currentMillis - lastOffDown > OFF_CLICK_TIMEOUT) {
    turn_off();
    lastOffDown = 0;
  }

  if (lastPrevDown && currentMillis - lastPrevDown > CLICK_TIMEOUT) {
    lastPrevDown = 0;
  }

  if (lastNextDown && currentMillis - lastNextDown > CLICK_TIMEOUT) {
    lastNextDown = 0;
  }
}

void check_ignition_key() {

  Keyboard.begin();
  Consumer.begin();

  pinMode(POWER_BUTTON_PIN, OUTPUT);
  analogWrite(POWER_BUTTON_PIN, 0);

  //turn_on();
}
