       bit(true, 6) |
       bit(not joy_sel_button, 5) |
       bit(not joy_sel_direction, 4) |
-      bit(true, 3) |
-      bit(true, 2) |
-      bit(true, 1) |
-      bit(true, 0)
+      bit(not ((joy_sel_button and joy_state_start) or (joy_sel_direction and joy_state_down)), 3) |
+      bit(not ((joy_sel_button and joy_state_sel) or (joy_sel_direction and joy_state_up)), 2) |
+      bit(not ((joy_sel_button and joy_state_b) or (joy_sel_direction and joy_state_left)), 1) |
+      bit(not ((joy_sel_button and joy_state_a) or (joy_sel_direction and joy_state_right)), 0)
     );
   } else {
     printf("warn: unhandled read from Joypad register: $%04X\n", address);

let joy_sel_button = false;
let joy_sel_direction = false;

def joy_reset() {
  joy_sel_button = false;
  joy_sel_direction = false;
}

def joy_write(address: uint16, value: uint8) {


  // Sprite Attribute Table (OAM): $FE00 – $FE9F
  if (address >= 0xFE00) and (address <= 0xFE9F) {
    // OAM cannot be accessed in modes 2 or 3
    let mode = mmu_read8(0xFF41) & 3;
    if mode == 3 or mode == 2 { return 0xFF; }

    return *(oam + (address & 0xFF));
  }

