;@xkas
HEADER
LOROM

!FreeRAM	= $13C0		;must be abs
!FreeSpace	= $2082B6	;(was20B02A)

ORG $00A0A3
BRA +
NOP #3
+

ORG $00C9EB		;NEW: Fix overworld mosaic screwup after you finish bonus level 000/100
BRA +
NOP #3
+


ORG $009F37
			JML MainFades
HijackReturn:		RTS

ORG !FreeSpace
reset bytes
db "STAR"
dw End-Begin-$01
dw End-Begin-$01^$FFFF

Begin:
MainFades:		LDA #$0F
			STA $0DAE
			INC !FreeRAM

			LDA #$22
			STA $41
			STA $42
			STA $43		;setup HDMA properties
			LDA #$20
			TSB $44
			LDA #$10
			TRB $44

			LDA !FreeRAM	;following wall of code sets up animated HDMA table algorithm-wise
			LDY $0DAF
			BNE +
			EOR #$FF
+			ASL A
			ASL A
			ASL A
			LDX #$0E
-			STZ $04A0,x
			STZ $04C0,x
			STZ $04E0,x
			STZ $0500,x
			STZ $0520,x
			STZ $0540,x
			STZ $0560,x
			STZ $0580,x
			STZ $05A0,x
			STZ $05C0,x
			STZ $05E0,x
			STZ $0600,x
			STZ $0620,x
			STZ $0640,x
			INC A
			CPX #$07
			BCS +
			DEC A
			DEC A
+			STA $04A1,x
			STA $04C1,x
			STA $04E1,x
			STA $0501,x
			STA $0521,x
			STA $0541,x
			STA $0561,x
			STA $0581,x
			STA $05A1,x
			STA $05C1,x
			STA $05E1,x
			STA $0601,x
			STA $0621,x
			STA $0641,x
			REP 2 : DEX
			BPL -
			EOR #$FF
			LDX #$0E
-			DEC A
			CPX #$07
			BCS +
			INC A
			INC A
+			STA $04B0,x
			STA $04D0,x
			STA $04F0,x
			STA $0510,x
			STA $0530,x
			STA $0550,x
			STA $0570,x
			STA $0590,x
			STA $05B0,x
			STA $05D0,x
			STA $05F0,x
			STA $0610,x
			STA $0630,x
			STA $0650,x
			PHA
			LDA #$FF
			STA $04B1,x
			STA $04D1,x
			STA $04F1,x
			STA $0511,x
			STA $0531,x
			STA $0551,x
			STA $0571,x
			STA $0591,x
			STA $05B1,x
			STA $05D1,x
			STA $05F1,x
			STA $0611,x
			STA $0631,x
			STA $0651,x
			PLA
			REP 2 : DEX
			BPL -

			LDA #$41		;\
			STA $4370		; |
			LDA #$26		; |
			STA $4371		; |Enable HDMA
			LDA.b #IndirectPtrs	; |
			STA $4372		; |
			LDA.b #IndirectPtrs>>8	; |
			STA $4373		; |
			LDA.b #IndirectPtrs>>16	; |
			STA $4374		; |
			STZ $4377		; |
			LDA #$80		; |HDMA enable
			TSB $0D9F		;/

			LDA !FreeRAM
			CMP #31
			BNE +

			LDA $0DAF
			BNE ++
			REP #$10
			LDX #$01BE
			LDA #$FF
-			STA $04A0,x		;clear HDMA table when done
			STZ $04A1,x
			DEX
			DEX
			BPL -
			SEP #$10

++			STZ !FreeRAM
			STZ $41
			STZ $42			;sets HDMA properties back to normal
			STZ $43
			LDA #$02
			STA $44

			LDA $0DAF		;Fading direction. $00 = Fadein, $01 = Fadeout
			EOR #$01		;reverse fading direction.
			STA $0DAF
			INC $0100		;Gamemode++;

			LDA #$80		;HDMA clear
			TRB $0D9F

+			JML HijackReturn

IndirectPtrs: 		db $F0 : dw $04A0	;Ptrs for indirect hdma
			db $F0 : dw $0580
			db $00
End:
print bytes