;***********************
;*** STARFIELD STUFF ***
;***********************
;
; a STAR is
; 1 state
; 2-3 base address
; 4 pos x
;
;level 4 variant

.STARS_Init

	ld A,(FRAME)	;sync with main scroll counter
	;inc A
	ld (STARS_Counter),A

;stars can move
	ld A,#3D
	ld (STARS_ForceNoMove),A

	;init sprite
	
	ld A,39
	call USPGADD
	
	;get first tile
	;inc HL	;global flag
	;inc HL	;tile flags
	;ld A,(HL)	;low addr
	;inc HL	
	;ld H,(HL)	;high addr
	;ld L,A
	
	;we got sprite , copy it
	;ld B,4
	ld IY,STARS_Sprite
	call FX_TranferStar
	
;.STARS_InitSprite_loop
;repeat 2
;	ld A,(HL)
;	ld (DE),A
;	inc L
;	inc E
;rend
	;ld C,(HL)
	;inc L
	;ld A,(HL)
	;inc L
	;ld (DE),A
	;inc E
	;ld A,C
	;ld (DE),A
	;inc E
	;djnz STARS_InitSprite_loop

	
;init tables
	
	ld IX,STARS_BufferA
	ld IY,STARS_table
	ld DE,4
	ld B,8
.STARS_Init_loop
	ld (IX+0),1	;set state
	;call STARS_Rnd	;get random Y
	ld A,(IY)
	inc IY
	;srl A
	;add 2
	
	add A	;*2
	add ATTR_Addr_low
	ld L,A
	ld H,ATTR_Addr_high
	
	ld A,(HL)		;setup base addr
	ld (IX+1),A
	inc L
	ld A,(HL)
	ld (IX+2),A
	
	;call STARS_Rnd	;get X
	ld A,(IY)	;get X
	inc IY
	ld (IX+3),A
	
	add IX,DE
	djnz STARS_Init_loop

	ret

.STARS_Counter
	db 0
	
.STARS_table	;y,x for 8 stars
	db 2,1		;0
	db 7,20		;1
	db 9,5		;0
	db 12,30	;1
	db 17,28	;0
	db 14,12	;1
	db 5,2		;0
	db 16,16	;1
	
.STARS_Run
	ld A,(LVL_End)
	or A
	ret nz


	ld A,15
	ld (STARS_Run_Speed),A
	
	ld HL,STARS_Sprite
	ld A,(STARS_Counter)
	and 15
	srl A
	srl A	
	add A	
	add L
	ld L,A
	ld (cur_STARS_Address),HL
	ld HL,STARS_BufferA

.STARS_Sub
	
	ld BC,#0804
	
.STARS_Run_loop1

	ld A,B
	exx
	ld HL,(cur_STARS_Address)
	and 1
	add A
	add A
	add A
	add L
	ld L,A
	ld (STARS_Address),HL
	exx

	ld A,(HL)
	or A
	jr z,STARS_Run_NoStar1
	
	push HL
	inc L
	ld E,(HL)
	inc L
	ld D,(HL)
	inc L
	
	
	ld A,(STARS_Counter)
STARS_Run_Speed	EQU $+1
	and 15
	jr nz,STARS_Run_NoMove
	ld A,(HL)
STARS_ForceNoMove	equ $
	dec A
	and 31
	ld (HL),A
.STARS_Run_NoMove
	ld A,(HL)
	add E
	ld E,A
	
	ld A,(DE)
	and 1	;check if we already have sprite here !
	jr nz,STARS_Run_NoDraw
	
	ex DE,HL
	ld (HL),6	;special star field !
	inc H
	inc H
STARS_Address EQU $+1
	ld DE,STARS_Sprite
	ld (HL),E
	inc H
	ld (HL),D

.STARS_Run_NoDraw
	pop HL
	
.STARS_Run_NoStar1
	ld A,C
	add L
	ld L,A
	djnz STARS_Run_loop1
	ret

.cur_STARS_Address	dw 0