# MIPS I system
# Copyright 2011-2012 Stefan Schuermans <stefan@blinkenarea.org>
# Copyleft GNU public license V2 or later
#          http://www.gnu.org/copyleft/gpl.html

SRCS=$(wildcard *.c)

PERL=perl
CC=mipsel-elf-gcc
LD=mipsel-elf-ld
OBJCOPY=mipsel-elf-objcopy
CFLAGS=-Wall -Wextra -fno-builtin -mips1 -mno-abicalls -Os
LFLAGS=-mips1

BASES=$(patsubst %.c,%,$(SRCS))
DEPS=$(addsuffix .d,$(BASES))
OBJS=$(addsuffix .o,$(BASES))

.PHONY: all clean
.SUFFIXES:
.SECONDARY:

all: rom.vhd ram.0.vhd ram.1.vhd ram.2.vhd ram.3.vhd

ifneq ($(MAKECMDGOALS),clean)
  include deps
endif

deps: $(DEPS)
	cat /dev/null $^ >$@

%.d: %.c Makefile
	$(CC) $(CFLAGS) -M -o $@ $<

%.o: %.c Makefile
	$(CC) $(CFLAGS) -c -o $@ $<

%.o: %.s Makefile
	$(CC) $(CFLAGS) -c -o $@ $<

fw.o: $(OBJS)
	$(LD) $(LFLAGS) -r -o $@ $^

fw: lnk.cmd boot.o fw.o
	$(LD) $(LFLAGS) -T lnk.cmd -o $@ boot.o fw.o

%.bin: fw
	$(OBJCOPY) -j .$(basename $@) -O binary $< $@

rom.vhd: rom.pl rom.bin
	$(PERL) rom.pl rom.bin >$@

ram.%.vhd: ram.pl ram.bin
	$(PERL) ram.pl ram.bin $(patsubst ram.%.vhd,%,$@) >$@

clean:
	rm -f $(DEPS) $(OBJS)
	rm -f boot.o fw.o fw
	rm -f rom.bin rom.vhd
	rm -f ram.bin ram.[0-3].vhd