PROJECT = max80
QU      = quartus

.SUFFIXES:

.SECONDARY:

.DELETE_ON_ERROR:

# Common options for all Quartus tools
QPRI    = --lower_priority
QCPF	= $(QU)_cpf $(QPRI)
QSH	= $(QU)_sh  $(QPRI)
QSTA	= $(QU)_sta $(QPRI)
QPGM    = $(QU)_pgm $(QPRI)

# Common options for Quartus in-flow tools
QOPT    = --write_settings_files=off $(QPRI)
QMAP    = $(QU)_map $(QOPT)
QFIT    = $(QU)_fit $(QOPT)
QCDB    = $(QU)_cdb $(QOPT)
QASM    = $(QU)_asm $(QOPT)
QPOW    = $(QU)_pow $(QOPT)

PERL    = perl

SRCDIRS = . ip scripts

outdir = output_files

alltarg := sof jic pow.rpt sta.rpt
allout   = $(foreach p,$(1),$(foreach o,$(alltarg),$(outdir)/$(p).$(o)))

all: $(call allout,$(PROJECT))

$(outdir)/%.map.rpt: %.qsf
	$(QMAP) $*

$(outdir)/%.fit.rpt: $(outdir)/%.map.rpt
	$(QFIT) $*

$(outdir)/%.mif_update.rpt: $(outdir)/%.fit.rpt
	$(QCDB) --update_mif $*

$(outdir)/%.sof: $(outdir)/%.mif_update.rpt
	$(QASM) $*

$(outdir)/%.sta.rpt: $(outdir)/%.fit.rpt | $(outdir)/%.sof
	$(QSTA) $*

$(outdir)/%.pow.rpt: $(outdir)/%.sta.rpt
	$(QPOW) $*

# XXX: do all .sof -> conversions using quartus_cpf
$(outdir)/%.jic:  %jic.cof $(outdir)/%.sof ../fw/dram.hex
	$(QCPF) --convert $<

# Clean out SignalTap
signalclean:
	$(PERL) -ne 'print unless (/(SIGNALTAP_FILE\b|\bENABLE_SIGNALTAP\b|\bSLD_FILE\b|SLD_NODE_)/);' < max80.qsf > max80.qsf.tmp
	mv -f max80.qsf.tmp max80.qsf

# Programming targets. Environment JTAG_CABLE can override the default,
# which is otherwise the first cable found.
rpar := )
JTAG_CABLE ?= $(shell jtagconfig --enum | sed -ne 's/^1$(rpar) //p')

# Transient programming
program:
	$(QPGM) -c '$(JTAG_CABLE)' -m JTAG -o 'p;$(outdir)/$(PROJECT).sof'

# Permanent programming in flash
flash:
	$(QPGM) -c '$(JTAG_CABLE)' -m JTAG -i -o 'pvbi;$(outdir)/$(PROJECT).jic'

%.deps: %.qsf scripts/qsfdeps.pl
	$(PERL) scripts/qsfdeps.pl $< $* > $@

clean:
	rm -rf db incremental_db simulation/modelsim \
	greybox_tmp */greybox_tmp iodevs.vh \
	$(outdir)/*.rpt $(outdir)/*.rpt \
	$(outdir)/*.summary $(outdir)/*.smsg \
	$(outdir)/*.htm $(outdir)/*.htm_files \
	$(outdir)/*.map $(outdir)/*.eqn $(outdir)/*.sld \
	$(outdir)/*.done

spotless:
	rm -rf $(outdir)

iodevs.vh: ../iodevs.conf ../tools/iodevs.pl
	$(PERL) ../tools/iodevs.pl v $< $@

# Verilog header dependencies
max80.sv: iodevs.vh

-include $(PROJECT).deps
