; VIA ports
PORTB = $6000
PORTA = $6001
DDRB  = $6002
DDRA  = $6003

; VIA masks
DDRA_NORMAL = %11100000
ALL_IN = %00000000
ALL_OUT = %11111111

PS2_RESET_BIT_NUMBER = 10

; Zero page variable locations
KEY_BUF_WRITE = $00  ; producer pointer into KEY_BUF
KEY_BUF_WRITE_HI = $01 ; always KEY_BUF_HI
PS2_BIT_NUMBER = $02 ; which bit will we read next?
PS2_NEXT_BYTE = $03  ; storage to decode PS/2 bits into bytes
PS2_IGNORE_NEXT_CODE = $04
KEY_BUF_READ = $05 ; consumer pointer into KEY_BUF
KEY_BUF_READ_HI = $06 ; always KEY_BUF_HI


; 1-page is the stack
THE_STACK_HI = $01

; 2-page is a circular buffer of the raw PS/2 bits (#0 or #1)
KEY_BUF_HI = $02      ; use Page 2 as circular buffer of PS/2 bits

E = %10000000
RW = %01000000
RS = %00100000

  .org $8000
reset:
  ; initialize stack pointer to $01FF
  ldx #$ff
  txs

  stz KEY_BUF_WRITE
  stz PS2_NEXT_BYTE
  stz PS2_IGNORE_NEXT_CODE
  stz KEY_BUF_READ

  lda #PS2_RESET_BIT_NUMBER
  sta PS2_BIT_NUMBER

  lda #KEY_BUF_HI
  sta KEY_BUF_WRITE_HI
  sta KEY_BUF_READ_HI


  lda #ALL_OUT ; Set all pins on port B to output
  sta DDRB

  lda #DDRA_NORMAL ; Set top 3 pins on port A to output
  sta DDRA

  cli

; Set mode
  lda #%00111000 ; Set 8-bit mode; 2-line display 5x8 font
  jsr lcd_instruction

; Display on/off
  lda #%00001111 ; Display on; cursor on ; blink on
  jsr lcd_instruction

; Entry mode set
  lda #%00000110 ; I/D: move direction inc/dec, S: display shift?
  jsr lcd_instruction

; Clear display
  lda #%00000001 ; Clear display
  jsr lcd_instruction

loop:

ps2_check_bit:
  lda KEY_BUF_READ
  cmp KEY_BUF_WRITE
  beq loop
  lda (KEY_BUF_READ)
  inc KEY_BUF_READ