# Configuration variables

Build = build
Pictures = pictures
Programs = programs

TeXSRC = ${wildcard *.tex}
PicSRC = ${notdir ${wildcard ${Pictures}/*.png}}
DemoSRC = ${notdir ${wildcard ${Programs}/*-demo.cfa}}
PgmSRC = ${notdir ${wildcard ${Programs}/*}}
RunPgmSRC = ${notdir ${wildcard ${Programs}/*.run.*}}
BibSRC = ${wildcard *.bib}

TeXLIB = .:../../LaTeXmacros:${Build}:		# common latex macros
BibLIB = .:../../bibliography			# common citation repository

#MAKEFLAGS = --no-print-directory # --silent
VPATH = ${Build} ${Pictures} ${Programs} # extra search path for file names used in document

DOCUMENT = uw-ethesis.pdf
BASE = ${basename ${DOCUMENT}}			# remove suffix

DemoTex = ${DemoSRC:%.cfa=${Build}/%.tex} 
RunPgmExe = ${addprefix ${Build}/,${basename ${basename ${RunPgmSRC}}}}
RunPgmOut = ${RunPgmExe:%=%.out}

# Commands

LaTeX = TEXINPUTS=${TeXLIB} && export TEXINPUTS && pdflatex -halt-on-error -output-directory=${Build}
BibTeX = BIBINPUTS=${BibLIB} && export BIBINPUTS && bibtex
CFA = cfa -O0 -g
CC  = gcc -O0 -g
CXX = g++-11 --std=c++20 -O0 -g

# Rules and Recipes

.PHONY : all fragments_ran clean			# not file names
.PRECIOUS : ${Build}/% ${Build}/%-demo      # don't delete intermediates
.ONESHELL :

all : fragments_ran ${DOCUMENT}

fragments_ran : $(RunPgmOut)

clean :
	@rm -frv ${DOCUMENT} ${Build}

# File Dependencies

%.pdf : ${TeXSRC} ${DemoTex} ${PicSRC} ${PgmSRC} ${BibSRC} Makefile | ${Build}
	${LaTeX} ${BASE}
	${BibTeX} ${Build}/${BASE}
	${LaTeX} ${BASE}
	# if needed, run latex again to get citations
	if fgrep -s "LaTeX Warning: Citation" ${basename $@}.log ; then ${LaTeX} ${BASE} ; fi
#	${Glossary} ${Build}/${BASE}
#	${LaTeX} ${BASE}
	cp ${Build}/$@ $@

${Build}:
	mkdir -p $@

%-demo.tex: %-demo | ${Build}
	$< > $@

${Build}/%-demo: ${Programs}/%-demo.cfa | ${Build}
	${CFA} $< -o $@

${Build}/%: ${Programs}/%.run.cfa | ${Build} # cfa cannot handle pipe
	sed -f ${Programs}/sedcmd $< > ${Build}/tmp.cfa; ${CFA} ${Build}/tmp.cfa -o $@

${Build}/%: ${Programs}/%.run.c | ${Build}
	sed -f ${Programs}/sedcmd $< | ${CC} -x c -I ${Programs} -o $@ -

${Build}/%: ${Programs}/%.run.cpp | ${Build}
	sed -f ${Programs}/sedcmd $< | ${CXX} -x c++ -I ${Programs} -o $@ -

${Build}/%.out: ${Build}/% | ${Build}
	$< > $@

-include ${Build}/*.d
