lorom
header

;$04/DBFB 8D FB 1D    STA $1DFB  [$04:1DFB]

;once at load

org $048E38
	sep #$30
	autoclean jml Music

org $04DBFB
	autoclean jml TestMusicChange

;every frame

org $048241
	autoclean jml MusicAll

org $0485BB	;unpatch old thing
	LDA 	#$08                
	STA.w	$007B	;original did not use DP

freecode

;*rats tag*

Music:
	ldx $1F11	;main OW only (only P1 ever gets used?)
	beq .new
.old                                      
	LDA.l $048D8A,x	;original music  
	bra .return
.new

	jsr GetMusicIndex
	LDA.l MusicTBL,x
	sta $13E6	;used later on
.return
	STA $1DFB	; Store value from table to the music register.
	PLB
	RTL

;---

MusicAll:
	lda $1F11	;main map only
	bne .submap
.mainmap
	jsr GetMusicIndex
	lda.l MusicTBL,x
	cmp $13E6	;want to change?
	beq .return
.change
	sta $1DFB	;different track, so change it
	sta $13E6	;new music index stored for future checks
.return
	phb		;restored code
	lda #$04
	pha : plb
	ldx #$01
	jml $048246	

.submap
	lda #$FF	;reset free RAM for next entry
	sta $13E6
	bra .return

;---

TestMusicChange:
	cpx #$00	;main map does not have this applied
	beq .hax
.submap
	sta $1DFB	;store original submap music
.return
	stz $1B9E
	jml $04DC01

.hax			;;; load music a bit earlier to reload the samples
	JSR GetMusicIndex
	LDA.l MusicTBL,x
	STA $13E6
	BRA .submap

;---

;OUT:
;X: music index for this position

GetMusicIndex:
	lda $1F21
	asl #3
	and #$F0
	pha
	lda $1F1F
	lsr
	ora $01,s
plx
tax
;remove the above two and uncomment these two if this breaks
;	sta $01,s
;	plx
	rts

MusicTBL:
db $70,$70,$70,$70,$70,$70,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C 
db $70,$70,$70,$70,$70,$70,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C 
db $70,$70,$70,$70,$70,$70,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C 
db $70,$70,$70,$70,$70,$70,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C 
db $70,$70,$70,$70,$70,$70,$70,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C 
db $70,$70,$70,$70,$70,$70,$70,$FF,$3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C 
db $70,$70,$70,$70,$70,$70,$70,$3C,$3C,$3C,$3C,$2B,$2B,$2B,$2B,$2B 
db $70,$70,$70,$70,$70,$70,$40,$3C,$3C,$3C,$2B,$2B,$2B,$2B,$2B,$2B 
db $70,$70,$70,$70,$70,$40,$40,$3C,$3C,$2B,$2B,$2B,$2B,$2B,$2B,$2B 
db $70,$70,$70,$70,$70,$40,$40,$40,$40,$2B,$2B,$2B,$2B,$2B,$2B,$2B 
db $70,$70,$70,$40,$40,$40,$40,$40,$40,$2B,$2B,$2B,$2B,$2B,$2B,$2B 
db $FF,$FF,$FF,$40,$40,$40,$40,$40,$40,$FF,$2B,$2B,$2B,$2B,$2B,$2B 
db $40,$40,$40,$40,$40,$40,$40,$40,$40,$40,$2B,$2B,$2B,$2B,$2B,$2B 
db $40,$40,$40,$40,$40,$40,$40,$40,$40,$40,$2B,$2B,$2B,$2B,$2B,$2B 
db $40,$40,$40,$40,$40,$40,$40,$40,$40,$40,$2B,$2B,$2B,$2B,$2B,$2B 
db $40,$40,$40,$40,$40,$40,$40,$40,$40,$40,$2B,$2B,$2B,$2B,$2B,$2B
