;************************
;*** STARFIELD STUFF ***
;************************
;
; a STAR is
; 1 state
; 2-3 base address
; 4 pos x
;
STARS_Counter		EQU BG_Counter
STARS_StopCommand	EQU BG_StopCommand

.STARS_Init

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

	ld IX,STARS_BufferA
	ld IY,STARS_table
	ld DE,4
	ld B,16
	
.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

	;init sprite
star_field_sprite EQU $+1	
	ld A,38
	call USPGADD
	ld IY,STARS_Sprite
	call FX_TranferStar
	
	;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
	
	;ld B,4
	;ld DE,STARS_Sprite
	
;.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
	
	ret
	
.STARS_table	;y,x for 16 stars
	;near
	db 2,1
	db 7,20
	db 9,5
	db 12,30
	db 14,12
	db 17,28
	db 5,2
	db 16,16
	;far
	db	3,5
	db	6,25
	db	8,15
	db	10,30
	db	13,10
	db	11,28
	db	15,19
	db	4,7






	
.STARS_Stop
	ld A,1
	ld (STARS_StopCommand),A
	ret
	
;***********************
;*** PLAY STARFIELD ***
;***********************	
	
.STARS_Run


	ld A,(STARS_Counter)
	inc A
	ld (STARS_Counter),A

	ld A,31
	ld (STARS_Run_Speed),A
	ld HL,STARS_Sprite
	ld A,(STARS_Counter)
	and 31
	srl A
	srl A
	srl A	
	add A	
	add L
	ld L,A
	ld (STARS_Address),HL
	ld HL,STARS_BufferA
	call STARS_Sub

	ld A,15
	ld (STARS_Run_Speed),A	
	ld HL,STARS_Sprite+8
	ld A,(STARS_Counter)
	and 15
	srl A
	srl A	
	add A	
	add L
	ld L,A
	ld (STARS_Address),HL
	ld HL,STARS_BufferB
	;call STARS_Sub
	
	
.STARS_Sub
	
	ld BC,#0804
	
.STARS_Run_loop1
	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)
	sub 1
	
	jr nc,STARS_Run_ValidateMove	
	push AF
	
	ld A,(STARS_StopCommand)
	or A
	jr nz,STARS_Kill
	
	pop AF
	
.STARS_Run_ValidateMove	
	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

.STARS_Kill
	pop AF
	pop HL
	ld (HL),0
	jr STARS_Run_NoStar1
	
;quick RND func from original code	
.STARS_Rnd
	LD HL,(SEED)
 	INC HL
	LD (SEED),HL
	LD A,(HL)
 	AND 31
	JR Z,STARS_Rnd
	RET
	