;; page 0 is visible at &0000-&ffff
;; 
;; Program Counter is 0. Interrupts are off.
;; Interrupt mode is 0. R should be 0.
;;
;; The contents of other registers are undefined.
;;
;; ASIC is locked.

org &0000

;; this is called when inserted into GX4000, Plus
jp main_start
defb "AMS"
;; offset 6, must be a JP. If not CSD just calls 0.
;; This is called when the CSD is running in timed mode, 
;; where it goes through each cartridge and runs them for
;; a short time
jp csd_auto_start						
;; offset 9, must be a JP. If not CSD just calls 0.
;; This is called when the CSD is running in non-timed mode (e.g. manual
;; selection).
jp csd_manual_start

;; here we setup a colour to show in the screen to indicate which code path was
;; taken

;; code path for auto start
csd_auto_start:
ld a,&40
ld (&4000),a		;; write to ram
jp start

;; code path for manual start
csd_manual_start:
ld a,&43
ld (&4000),a		;; write to ram
jp start

;; code path for normal start
main_start:
ld a,&54			;
ld (&4000),a		;; write to ram
jp start


;; perform setup to ensure hardware is in a known state
start:
di					;; disable interrupts
im 1					;; set interrupt mode 1
ld bc,&f782			;; setup initial PPI port directions
out (c),c
ld bc,&f400			;; set initial PPI port A (AY)
out (c),c
ld bc,&f600			;; set initial PPI port C (AY direction)
out (c),c

ld bc,&7fc0			;; set initial RAM configuration
out (c),c

;; unlock ASIC so we can access ASIC registers
ld b,&bc
ld hl,sequence
ld e,17
seq:
ld a,(hl)
out (c),a
inc hl
dec e
jr nz,seq

;; set initial CRTC settings (screen dimensions etc)
ld hl,end_crtc_data
ld bc,&bc0f
crtc_loop:
out (c),c
dec hl
ld a,(hl)
inc b
out (c),a
dec b
dec c
jp p,crtc_loop

ld hl,&c9fb
ld (&0038),hl
ei

;; enable asic ram (will be visible in range &4000-&7fff)
ld bc,&7fb8
out (c),c


;; set pen 0 and border colours to show code path we came from
;; in a normal game we would check and change what code path we take
ld a,(&4000)
ld bc,&7f00
out (c),c
or &40
out (c),a
ld c,&10
out (c),c
out (c),a

;; your code here
loop:

jr loop

;; your crtc setup values here; these are examples
crtc_data:
defb &3f, &28, &2e, &8e, &26, &00, &19, &1e, &00, &07, &00,&00,&30,&00,&c0,&00
end_crtc_data:

;; sequence to unlock asic
sequence:
defb &ff,&00,&ff,&77,&b3,&51,&a8,&d4,&62,&39,&9c,&46,&2b,&15,&8a,&cd,&ee

end