BUILD = build

all: $(BUILD)/stage1-hex1 $(BUILD)/stage1-elf $(BUILD)/stage0

stage0-hex0: $(BUILD)/stage0-hex0

# We need an initial compiler to convert the hex0.in file into an executable that can be used to generate the stage0 compiler.
$(BUILD)/stage0-bootstrap: hex0/hex0.in
	for x in `sed '/^;/d;s/;.*//;s/ *//' hex0/hex0.in`; do printf \\x$$x; done > $@
	chmod +x $@

# We use the stage0-bootstrap compiler to generate the stage0-hex0 compiler.
$(BUILD)/stage0-hex0: $(BUILD)/stage0-bootstrap
	$< < hex0/hex0.in > $@
	chmod +x $@

# Finally, we use the stage0-hex0 compiler to generate the stage0 compiler, which should be identical to the stage0-hex0 compiler.
$(BUILD)/stage0: $(BUILD)/stage0-hex0
	$< < hex0/hex0.in > $@
	chmod +x $@

verify-hex0: $(BUILD)/stage0
	cmp $(BUILD)/stage0 $(BUILD)/stage0-hex0

$(BUILD)/stage1-elf: $(BUILD)/stage0
	$< < hex1/elf.in > $@
	chmod +x $@

$(BUILD)/stage1-hex1.text: $(BUILD)/stage0
	$< < hex1/hex1.in > $@

$(BUILD)/stage1-hex1: $(BUILD)/stage1-elf $(BUILD)/stage1-hex1.text
	$(BUILD)/stage1-elf $(BUILD)/stage1-hex1 $(BUILD)/stage1-hex1.text
	chmod +x $@

verify-hex1: $(BUILD)/stage1-elf $(BUILD)/stage1-hex1
	$(BUILD)/stage1-hex1 < hex1/helloworld.h1 > $(BUILD)/helloworld.text
	$(BUILD)/stage1-elf $(BUILD)/helloworld.elf $(BUILD)/helloworld.text
	chmod +x $(BUILD)/helloworld.elf
	$(BUILD)/helloworld.elf


clean:
	rm -rf $(BUILD)
	mkdir -p $(BUILD)
