# app.mk — shared Makefile fragment for any standalone Sprinter ESTEX
# program — used both by libc feature tests under tests/ and by real
# applications under examples/.
#
# Usage in a per-program Makefile:
#
#   PROJ_ROOT := $(abspath $(CURDIR)/../..)
#   EXAMPLE   := my_program          # base name (matches my_program.c)
#
#   # Optional overrides (any combination):
#   # MEMORY     := small             # tiny | small | big | huge | manual
#   # STACK_SIZE := 2048              # bytes reserved for the stack
#   # EXTRA_SRCS := helper.c util.c   # additional .c files in this dir
#   # EXTRA_FLAGS := --crt0=minimal   # passed through to sprinter-cc
#   # EXTRA_DATA := test.txt          # extra files to add to `make floppy`
#
#   include $(PROJ_ROOT)/app.mk
#
# Pipeline (all driven by sprinter-cc):
#   crt0 + EXAMPLE.c + EXTRA_SRCS  --sdcc-->  .ihx
#   .ihx                            --mkexe--> EXAMPLE.exe
# linking against lib/sprinter.lib for libc.
#
# Targets provided:
#   all      build $(EXAMPLE).exe                                   (default)
#   clean    remove build artefacts
#   floppy   build the example and pack it (alone, plus EXTRA_DATA) into
#            mame/v306/IMG/mc.img — useful for trying a single program
#            without rebuilding every example.  Top-level `make floppy`
#            (in the repo root) still packs all examples.
#   run      floppy + launch MAME

SPRINTER_CC := $(PROJ_ROOT)/bin/sprinter-cc
MKEXE       := $(PROJ_ROOT)/toolchain/mkexe/mkexe
LIB         := $(PROJ_ROOT)/lib/sprinter.lib

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

# Optional knobs — see top of file.
MEMORY      ?= tiny
SOURCES     := $(EXAMPLE).c $(EXTRA_SRCS)

CC_FLAGS    := --memory $(MEMORY)
ifneq ($(STACK_SIZE),)
CC_FLAGS    += --stack-size $(STACK_SIZE)
endif
CC_FLAGS    += $(EXTRA_FLAGS)

all: $(EXAMPLE).exe

$(EXAMPLE).exe: $(SOURCES) $(MKEXE) $(LIB)
	$(SPRINTER_CC) $(CC_FLAGS) -o $@ $(SOURCES)

$(MKEXE):
	$(MAKE) -C $(PROJ_ROOT)/toolchain/mkexe

$(LIB):
	$(MAKE) -C $(PROJ_ROOT)/lib

clean:
	rm -rf .sprinter-cc-* $(EXAMPLE).exe

# `make floppy` packs ONLY this program (+ optional EXTRA_DATA files) into
# the MAME floppy image, replacing whatever was there.  Handy for trying a
# single program without rebuilding everything.
floppy: $(EXAMPLE).exe
	python3 $(MAKE_DISK) $(FLOPPY_IMG) $(EXAMPLE).exe $(EXTRA_DATA)
	@echo
	@echo "Floppy ready: $(FLOPPY_IMG) (with $(EXAMPLE).exe$(if $(EXTRA_DATA), + $(EXTRA_DATA))) "
	@echo "Run:  cd $(MAME_DIR) && ./run_mame.sh"

run: floppy
	cd $(MAME_DIR) && ./run_mame.sh

.PHONY: all clean floppy run
