; movie format 1
; word: first screen format
; byte: # of frames
; frame data

; frame format:
;  # of changes
;  byte: offset to next byte
;  changed byte

; hl = movie ptr
; written by Erik Huizing
; ehuizing@acs.ucalgary.ca
; Thanks to Josh Morris for the idea to make
; a movie player

MAXCHANGES EQU 254

PlayMovie:
 ld de, (PROGRAM_ADDR)
 add hl, de		; get proper address
 push hl
 CALL LD_HL_MHL		; fetch first frame
 add hl, de
 ld de, GRAPH_MEM
 ld bc, 256
 ldir

 pop hl
 inc hl
 inc hl
 ld a, (hl)
 or a
 ret z			; no frames
 inc hl
_pmFrameLoop:

 push af
 ld a, (hl)
 inc hl
 or a
 jr z, _pmWaitFrame 	; no changes to this frame
 push af
 ld c, 0x00
 ld b, a	; # of changes
 ld de, GRAPH_MEM

_pmFrameChanges:
 ld a, (hl) ; get byte offset
 add a, e
 jr nc, _pmNoIncD
 inc d
_pmNoIncD:
 ld e, a		; de = de + a
 inc hl
 push bc
 ldi			; (de) = (hl)
 dec de
 pop bc
 djnz _pmFrameChanges	; next changes

 push hl
 ld hl, GRAPH_MEM
 ld de, VIDEO_MEM + 16*16+4
 ld a, 32
_pmCopyRow:
 ld bc, 8
 ldir
 ex de, hl
 ld bc, 8
 add hl, bc
 ex de, hl		; de = de + 8
 dec a
 jr nz, _pmCopyRow
 pop hl

 pop af			 ; restore # of changes
_pmWaitFrame: ; a = # of changes for frame
 ld b, a
 ld a, MAXCHANGES+1	
 sub b
 sra a
 sra a
 sra a
 sra a
 and %00011111
 ld b, a			; wait for (MAXCHANGES - 
_pmWaitLoop:		; # of changes)/8
 halt			   ; less changes = longer wait
 djnz _pmWaitLoop
 push hl
 CALL GET_KEY
 pop hl
 or a
 jr z, _pmCont
 pop hl
 ret
_pmCont:
 pop af
 dec a
 jr nz, _pmFrameLoop	; next frame
ret
