# Sprinter C Compiler — top-level Makefile
#
#   make             build host tools, libc archive, and all examples
#   make tools       build only host tools (mkexe)
#   make lib         build lib/sprinter.lib (libc archive used by sprinter-cc)
#   make examples    build all examples
#   make floppy      package every example + test files into mame/v306/IMG/mc.img
#   make check       run mkexe unit tests
#   make clean       remove all build artefacts
#   make sdcc        download/extract vendored SDCC
#
# Most heavy lifting is delegated to sub-Makefiles.

EXAMPLES := hello banked bankedbg strtest cat seek malloc mem_test argv errno rt_test openenv ls conio attrprob timedir mouse banklocl stdlib assrtest ptime stattest filetest gfx_demo gfx_d16 gfx_text gfx_mous

MAME_DIR    := mame/v306
FLOPPY_IMG  := $(MAME_DIR)/IMG/mc.img
MAKE_DISK   := $(MAME_DIR)/make_disk.py

EXE_FILES := \
    examples/hello/hello.exe       \
    examples/banked/banked.exe     \
    examples/bankedbg/bankedbg.exe \
    examples/strtest/strtest.exe   \
    examples/cat/cat.exe           \
    examples/seek/seek.exe         \
    examples/malloc/malloc.exe     \
    examples/mem_test/mem_test.exe \
    examples/argv/argv.exe         \
    examples/errno/errno.exe       \
    examples/rt_test/rt_test.exe   \
    examples/openenv/openenv.exe   \
    examples/ls/ls.exe             \
    examples/conio/conio.exe       \
    examples/attrprob/attrprob.exe \
    examples/timedir/timedir.exe   \
    examples/mouse/mouse.exe       \
    examples/banklocl/banklocl.exe \
    examples/stdlib/stdlib.exe     \
    examples/assrtest/assrtest.exe \
    examples/ptime/ptime.exe       \
    examples/stattest/stattest.exe \
    examples/filetest/filetest.exe \
    examples/gfx_demo/gfx_demo.exe \
    examples/gfx_d16/gfx_d16.exe   \
    examples/gfx_text/gfx_text.exe \
    examples/gfx_mous/gfx_mous.exe

DATA_FILES := \
    examples/cat/test.txt          \
    examples/seek/big.txt

.PHONY: all tools lib examples check clean sdcc floppy $(EXAMPLES)

all: tools lib examples

tools:
	$(MAKE) -C toolchain/mkexe

lib:
	$(MAKE) -C lib

check: tools
	$(MAKE) -C toolchain/mkexe check

examples: $(EXAMPLES)

$(EXAMPLES): tools lib
	$(MAKE) -C examples/$@

# Generate big.txt if missing (gen_bigfile.py creates 100 KB marker file).
examples/seek/big.txt:
	cd examples/seek && python3 gen_bigfile.py big.txt 102400

# Re-pack the MAME floppy image with every built example + needed data files.
floppy: examples examples/seek/big.txt
	python3 $(MAKE_DISK) $(FLOPPY_IMG) $(EXE_FILES) $(DATA_FILES)
	@echo
	@echo "Floppy ready: $(FLOPPY_IMG)"
	@echo "Run:  cd $(MAME_DIR) && ./run_mame.sh"

clean:
	$(MAKE) -C toolchain/mkexe clean
	$(MAKE) -C lib clean
	@for e in $(EXAMPLES); do $(MAKE) -C examples/$$e clean; done

sdcc:
	bash third_party/setup-sdcc.sh
