;##################################################################
;
;   Allecto-Z80 (low-level support routines)
;
;   Programmed by Patrick Davidson (pad@calc.org)
;        
;   This program is in the public domain.  There is no warranty.
;
;   This file was last modified March 30, 2001.
;
;##################################################################   

;############## Synchronization

synchronize:
        ld      hl,timer
        ld      a,(speed)
        cp      (hl)
        jr      c,too_slow

loop_wait:
        cp      (hl)            ; Test value of 4 - (timer)
        jr      nc,loop_wait    ; NC : timer <= 4
        ld      (hl),0

;        ld      a,(CONTRAST)
;        out     (2),a
        ret      

too_slow:
        ld      (hl),0
;        ld      a,(CONTRAST)
;        dec     a
;        dec     a
;        out     (2),a

        ret

timer_interrupt:
        push    af
        in      a,(3)
        bit     1,a
        jr      z,int_exit
        ld      a,(in_game)
        or      a
        jr      nz,timer_swapping
        ld      a,$7c
        out     (0),a
        ld      a,(timer)
        inc     a
        ld      (timer),a
int_exit:
        pop     af
        ret

timer_swapping:
        push    hl
        ld      hl,timer
        inc     (hl)
        ld      a,(speed)
        cp      (hl)
        jr      nz,ie2

which_page:
        ld      a,0
        cpl
        ld      (which_page+1),a
        or      a
        jr      z,main_screen

smc_alloc_page:
        ld      a,$a
        out     (0),a
        ld      hl,$fc00
        ld      (gfx_target),hl
        pop     hl
        pop     af
        ret

main_screen:
        ld      a,$7c
        out     (0),a
smc_alloc_start:
        ld      hl,$ca00
        ld      (gfx_target),hl
ie2:    pop     hl
        pop     af
        ret
timer_interrupt_end:

;############## Low-level support routines

table_look_up:
        add     a,a
        ld      hl,speed_table
ADD_HL_A:
        add     a,l
        ld      l,a
        ret     nc
        inc     h
        ret

FAST_RANDOM:
        push    hl
        ld      hl,0
        ld      a,(hl)
        inc     hl
        xor     (hl)
        inc     hl
        xor     (hl)
        inc     hl
        res     6,h
        ld      (FAST_RANDOM+2),hl
        pop     hl
        ret
        ret
