   // ---------------------------------
   // Left mouse button state update
   // ---------------------------------
-  if (!(PINB & 0b1000) && !leftButton)
-  {
-    Mouse.press(MOUSE_LEFT);
-    leftButton = true;
-  }
-  else
-  {
-    if ((PINB & 0b1000) && leftButton)
-    {
-      Mouse.release(MOUSE_LEFT);
-      leftButton = false;
-    }
-  }
+  ReadButton(leftButton);
+  UpdateButton(leftButton);
 
   // ---------------------------------
   // Right mouse button state update
   // ---------------------------------  
-  if (!(PINB & 0b0100) && !rightButton)
-  {
-    Mouse.press(MOUSE_RIGHT);
-    rightButton = true;
-  }
-  else
-  {
-    if ((PINB & 0b0100) && rightButton)
-    {
-      Mouse.release(MOUSE_RIGHT);
-      rightButton = false;
-    }
-  }
+  ReadButton(rightButton);
+  UpdateButton(rightButton);
   
   // ---------------------------------
   // Middle mouse button state update
   // ---------------------------------
-  if (!(PINB & 0b0010) && !middleButton)
-  {
-    Mouse.press(MOUSE_MIDDLE);
-    middleButton = true;
-  }
-  else
-  {
-    if ((PINB & 0b0010) && middleButton)
-    {
-      Mouse.release(MOUSE_MIDDLE);
-      middleButton = false;
-    }
-  }
+  ReadButton(middleButton);
+  UpdateButton(middleButton);
 
   // Wait a little before next update
   delay(10);

/* ================================================================================
   Author  : GuilleAcoustic
   Date    : 2015-05-22
   Revision: V1.0
   Purpose : Opto-mechanical trackball firmware
   --------------------------------------------------------------------------------
   Wiring informations: Sparkfun Pro micro (Atmega32u4)

  yAxis.index       = (yAxis.index << 2) | ((PIND & 0b00001100) >> 2);
  yAxis.coordinate += lookupTable[yAxis.index & 0b00001111];
}

// =================================================================================
// Functions
// =================================================================================
void ReadButton(BUTTON_& button)
{
  // Variables
  long    currentime;
  boolean switchState;
  boolean debounced;
  
  // Get current time
  currentime = millis();
  debounced  = (currentime - button.lastDebounceTime > DEBOUNCE_THREASHOLD);

  // Get current switch state
  switchState = !(PINB & button.bitmask);

  // Button state acquisition
  if ((switchState != button.state) && debounced)
  {
    button.lastDebounceTime = currentime;
    button.state            = switchState;
    button.needUpdate       = true;
  }
}

void UpdateButton(BUTTON_& button)
{
  if (button.needUpdate)
  {
    (button.state) ? Mouse.press(button.button) : Mouse.release(button.button);
    button.needUpdate = false;
  }
}
