( PS/2 keyboard handler                      JCB 18:29 11/21/10)

module[ ps2kb"

variable kbread
variable kbstate

\ E=END(1) S=START(0) P=PARITY
\ F9 is code 01  E P 0 0  0 0 0 0  0 1 S 1
\ += is code 55  E P 0 1  0 1 0 1  0 1 S 1

: ps2listening
    ps2_clk_dir in
    ps2_dat_dir in
;
: kbfifo@
    dup d# 4 rshift 2* kbfifo + @
    swap d# 15 and rshift d# 1 and
;
: kbnew ( -- ) \ new byte
    h# 800 kbstate !
;
: kbfifo-cold
    kbfifocount @ kbread !
    kbnew
;
: kbfifo-fullness ( -- u ) \ how many unread bits in the kbfifo
    kbfifocount @ kbread @ - h# ff and
;

h# 80 constant KESC
h# 81 constant KF1
h# 82 constant KF2
h# 83 constant KF3
h# 84 constant KF4
h# 85 constant KF5
h# 86 constant KF6
h# 87 constant KF7
h# 88 constant KF8
h# 89 constant KF9
h# 8a constant KF10
h# 8b constant KF11
h# 8c constant KF12

meta
    : x[
        base @ hex
        pad
        begin
            bl parse 2dup s" ]" compare
        while
            0. 2swap >number throw 2drop
            over c!
            1+
        repeat
        2drop
        pad - pad swap
        dup tc, 0 do dup c@ tc, 1+ loop drop
        base !
    ;
target

create alphas
x[ 1c 32 21 23 24 2B 34 33 43 3B 42 4B 3A 31 44 4D 15 2D 1B 2C 3C 2A 1D 22 35 1A ]
\   a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  p  q  r  s  t  u  v  w  x  y  z

create numbers
x[ 45 16 1E 26 25 2E 36 3D 3E 46 4c ]
\   0  1  2  3  4  5  6  7  8  9  :  ;  <  =  >  ?  


create 20-2Funshifted
x[ 29    00 00 00 00 00 00 0e 00 00 00 00 41 4e 49 4a ]
\  SPACE  !  "  #  $  %  &  ´  (  )  *  +  ,  -  .  /

create 20-2fshifted
x[ 29    16 52 26 25 2e 36 00 46 45 3e 55 00 00 00 00 ]
\  SPACE  !  "  #  $  %  &  ´  (  )  *  +  ,  -  .  /

: kbbyte
    hex4 cr
;

: kbbit
    d# 11 lshift kbstate @ 2/ or
    dup kbstate !
    d# 1 and if
        kbstate @ d# 2 rshift h# ff and kbbyte
        kbnew
    then
;
: kbfifo-proc
    begin
        kbfifo-fullness ?dup
    while
        1- kbfifo@ kbbit
        d# 1 kbread +!
    repeat
;
]module