;******************
;*** LEVEL 6 BG ***
;******************

;bg element
;byte x
;byte counter (cycle 32 , 16 steps >15 = no draw)
;byte y

L6BG_MaxElements	EQU 16
L6BG_counter		EQU BG_Buffer+48 ;allow to be saved

.L6BG_Init

	ld A,(FRAME)
	inc A
	ld (L6BG_counter),A
	
	ld HL,L6BG_InitTable
	ld DE,BG_Buffer
	ld BC,L6BG_MaxElements*3
	ldir

	ret

;init table - 16 objects x,state,y
.L6BG_InitTable
;group A 0/16 green
	db 7,0,5
	db 7,0,6
	db 7,16,8
	
	db 22,16,12
	db 22,16,13
	db 22,0,15

	db 14,0,10
	db 15,16,10

;group B 8/24 red
	db 22,8,5
	db 22,8,6
	db 22,24,8
	
	db 7,8,12
	db 7,8,13
	db 7,24,15
	
	db 0,8,10
	db 1,24,10
	
.L6BG_Run

	ld A,(NOSCROLL)
	or A
	jr nz,L6BG_RunNoScroll

	ld A,(L6BG_counter)
	inc A
	ld (L6BG_counter),A
	
	and 7
	srl A
	ld (L6BG_CurrentSprOffset),A		

.L6BG_RunNoScroll	

	ld HL,L6BG_SprTable
	ld (L6BG_SprRef),HL
	
	ld B,8
	ld HL,BG_Buffer
	call L6BG_RunLoop
	
	ld HL,L6BG_SprTable2
	ld (L6BG_SprRef),HL
	ld B,8
	ld HL,BG_Buffer+24
	
.L6BG_RunLoop
	ld E,(HL)

	ld A,(NOSCROLL)
	or A
	jr nz,L6BG_RunLoopNoMove
	
	ld A,(L6BG_counter)
	and 7
	jr nz,L6BG_RunLoopNoMove
	
	ld A,E
	dec A
	and 31
	ld E,A
	ld (HL),E
	
.L6BG_RunLoopNoMove	
	inc L
	ld A,(HL)
	inc A
	and 31
	ld (HL),A
	cp 16
	jr nc,L6BG_RunNoDraw
	
	push BC
	push HL
	
	ld C,E
	inc L
	ld B,(HL)
	
L6BG_SprRef	EQU	$+1
	ld HL,L6BG_SprTable
	
	srl A
	ld E,A
	ld D,0
	add HL,DE
	ld A,(HL)
	
L6BG_CurrentSprOffset	EQU $+1
	add 0

	call TSPGADD
	call SPNS	

	pop HL
	pop BC
	
.L6BG_RunNoDraw
	inc L
	inc L
	djnz L6BG_RunLoop
	

	ret
	
.L6BG_SprTable
	db 60,56,52,48,52,56,60,60
.L6BG_SprTable2
	db 76,72,68,64,68,72,76,76

	