#
# Makefile for P-50 Tiny BASIC
#
# Copyright (c) 2026 Large Scale Systems Museum
# By Dave McGuire <mcguire@lssmuseum.org>
#
# The interpreter is written as a set of separately-maintained source
# files (listed in SRCS below, in assembly order). There is no linker
# in this toolchain, so p50asm must assemble them as one single source
# file: this Makefile cats them together in order, assembles the
# result, and then removes the concatenated file, leaving only the
# component sources plus the generated tape and listing.
#
# Targets:
#   all            build the tape and listing (the default)
#   dist           create p50-tiny-basic-<version>.tar.bz2, with the
#                  version taken from version.p50, containing everything
#                  needed to build and use the interpreter (and nothing
#                  from Subversion)
#   clean          remove everything the other targets build
#

P50ASM = p50asm
ENTRY = BOOT

NAME = tinybasic_full
MERGED = $(NAME).p50
TAPE = $(NAME).p50tap
LISTING = $(NAME).lst

# iostmt.p50 must stay last: it holds the program's only END.
SRCS = io0.p50 \
       lexcore.p50 \
       tokenize.p50 \
       linestore.p50 \
       eval.p50 \
       stmt.p50 \
       ctrlflow.p50 \
       ifcmd.p50 \
       listcmd.p50 \
       boot.p50 \
       version.p50 \
       numparse2.p50 \
       forloop.p50 \
       iostmt.p50

PROGNAME = p50-tiny-basic

# The version is decoded from VERSTR's one-character-per-line OCT
# codes in version.p50, so that file is its only source.
VERSION := $(shell awk '/^VERSTR/ { f = 1 } \
	f { v = substr($$0, 12); sub(/ .*/, "", v); if (v == "0") exit; \
	    n = 0; for (i = 1; i <= length(v); i++) \
	    n = n * 8 + substr(v, i, 1); printf "%c", n }' version.p50)
DISTDIR = $(PROGNAME)-$(VERSION)

# Everything that goes into the distribution. These are explicit lists
# rather than wildcards so that editor backups, build products, and
# local scratch files can't end up in a release.
DOCS = docs/MANUAL.md docs/QUICKREF.md docs/DESIGN.md docs/LICENSE.md
DISTFILES = README.md Makefile tinybasic.cfg $(SRCS) $(DOCS)

.PHONY: all dist clean

all: $(TAPE) $(LISTING)

# Grouped target (requires GNU Make 4.3+, e.g. Ubuntu 24.04's default
# make): both outputs come from one p50asm invocation, so they must
# share a single recipe run rather than each re-running it.
$(TAPE) $(LISTING) &: $(MERGED)
	$(P50ASM) -e $(ENTRY) -o $(TAPE) $(MERGED)
	rm -f $(MERGED)

$(MERGED): $(SRCS)
	cat $(SRCS) > $(MERGED)

dist:
	@rm -rf $(DISTDIR)
	@rm -f $(DISTDIR).tar.bz2
	@mkdir $(DISTDIR)
	@for f in $(DISTFILES); do \
		mkdir -p $(DISTDIR)/`dirname $$f` && \
		cp -p $$f $(DISTDIR)/$$f || exit 1; \
	done
	@tar -cjf $(DISTDIR).tar.bz2 $(DISTDIR)
	@rm -rf $(DISTDIR)
	@echo Distribution file $(DISTDIR).tar.bz2 created.

clean:
	rm -f $(MERGED) $(TAPE) $(LISTING)
