# Full path to the nasm executable
NASM=nasm

# Soundblaster base ports
PORTS=210 220 230 240 250 260 280

DRIVER_DRVS=$(addprefix u6sb/u6sb_,$(addsuffix .drv,$(PORTS)))
DRIVER_BINS=$(addprefix temp/u6sb_,$(addsuffix .bin,$(PORTS)))
CP_BINS=$(addsuffix .bin,$(addprefix temp/codepatch_,$(PORTS)))
JP_BINS=temp/jumppatch_1.bin temp/jumppatch_2.bin

BINPATCHER=binpatcher/binpatcher
U6DECODE=u6decode/u6decode
U6ENCODE=u6encode/u6encode

BINPATCHER_CLEAN=binpatcher_clean
U6DECODE_CLEAN=u6decode_clean
U6ENCODE_CLEAN=u6encode_clean

BINARIES=$(BINPATCHER) $(U6DECODE) $(U6ENCODE)

MAKEFILES=$(addsuffix Makefile,$(dir $(BINARIES)))

all: temp u6sb $(DRIVER_DRVS)

include $(MAKEFILES)

# u6sb/u6sb_xxx.drv  <--  temp/u6sb_xxx.bin + u6encode/u6encode
$(DRIVER_DRVS): u6sb/%.drv: temp/%.bin $(U6ENCODE)
	@$(U6ENCODE) $< $@
	@echo Port 0x$(patsubst u6sb_%,%,$*) finished

# temp/u6sb_xxx.bin  <--  temp/u6roland.bin + temp/codepatch_xxx.bin + temp/jumppatch_x + binpatcher/binpatcher
$(DRIVER_BINS): temp/u6sb_%.bin: temp/u6roland.bin temp/codepatch_%.bin $(JP_BINS) $(BINPATCHER)
	@cat --binary $< temp/codepatch_$*.bin > $@
	@$(BINPATCHER) $@ 623 temp/jumppatch_1.bin
	@$(BINPATCHER) $@ 652 temp/jumppatch_2.bin

# temp/codepatch_xxx.bin  <--  source/codepatch.asm
$(CP_BINS): temp/codepatch_%.bin: source/codepatch.asm
	@$(NASM) -f bin $< -o $@ -dsb_base_port=0x$*

# temp/jumppatch_x.bin  <--  source/jumppatch.asm
temp/jumppatch_1.bin: source/jumppatch.asm
	@$(NASM) -f bin $< -o $@ -dpatch_start=623 -dpatch_end=650 -dfile_size=1465 -djmp_dest=jmp_1
temp/jumppatch_2.bin: source/jumppatch.asm
	@$(NASM) -f bin $< -o $@ -dpatch_start=652 -dpatch_end=668 -dfile_size=1465 -djmp_dest=jmp_2

# temp/u6roland.bin  <--  source/u6roland.drv + u6decode/u6decode
temp/u6roland.bin: source/u6roland.drv $(U6DECODE)
	@$(U6DECODE) $< $@

temp:
	@mkdir temp
u6sb:
	@mkdir u6sb

clean: $(BINPATCHER_CLEAN) $(U6DECODE_CLEAN) $(U6ENCODE_CLEAN) clean_temp
clean_temp:
	rm -rf temp
clean_u6sb:
	rm -rf u6sb
