# gmake-format makefile for Justin's thesis

MAINFILE = thesis.tex

SUBFILES = defs.tex lengths.tex abstract.tex ack.tex ded.tex \
	$(wildcard appen*.tex) $(wildcard chap*.tex) \
	tailpage.tex

# xfig drawings to be included in the document
FIGFILES = $(wildcard fig/*.fig)

# other postscript files to be included in the document
EPSFILES = $(wildcard eps/*.eps)

BIBFILES = $(wildcard *.bib)

# constants

make = gmake
latex = latex2e
bibtex = bibtex
fig2dev = fig2dev
printer = radar

MAIN = $(subst .tex,,${MAINFILE})
MAINBBL = ${MAIN}.bbl
MAINDVI = ${MAIN}.dvi
MAINAUX = ${MAIN}.aux
MAINTOC = ${MAIN}.toc
MAINLOG = ${MAIN}.log
MAINPS = ${MAIN}.ps

# file where we measure our progress by bytes, words, lines and pages
WCLOGFILE = ${MAIN}.wc
REBIBFLAG = ${MAIN}.must_remake_bbl.flag


# COMMANDS

.PHONY: dvi ps print xdvi gv backup clean grep latex_doit bibtex_doit

dvi:	${WCLOGFILE}

ps:	dvi ${MAINPS}

print:	ps
	lpr -P${printer} ${MAINPS}
	lpq -P${printer}

xdvi:	dvi
	xdvi -s 4 ${MAINDVI}

gv:	ps
	gv ${MAINPS}

backup:
	test -d backup || mkdir backup
	tar cvf backup/`date +%y-%m-%d`.tar Makefile NOTES $(MAINFILE) $(SUBFILES) $(FIGFILES) $(EPSFILES) $(BIBFILES) $(WCLOGFILE) ; gzip -f backup/*.tar

clean:	
	rm -f *.dvi
	rm -f *.aux
	rm -f *.log
	rm -f *.toc
	rm -f *.lof
	rm -f *.lot
	rm -f *.idx
	rm -f *.ind
	rm -f *.ilg
	rm -f *.bbl
	rm -f *.blg
	rm -f ${FIGFILES:.fig=.eps}
	rm -f ${MAINPS}

# e.g. gmake grep string='traveling salesman'
grep:
	@echo '*****' Searching for '"'$(string)'"' in thesis files '*****'
	@fgrep -i -e '$(string)' ${MAINFILE} ${SUBFILES} ${BIBFILES}


# RULES

# kill some default rules
.SUFFIXES:

${WCLOGFILE}:	${MAINDVI}
	./wordcount ${MAIN} >> ${WCLOGFILE}
        # after every successful compile, log word count to WCLOGFILE.

${MAINDVI}:	${MAINFILE} ${SUBFILES} ${EPSFILES} ${FIGFILES:.fig=.eps} ${MAINBBL}
	${make} latex_doit || echo continue
	@echo maybe remake bibliography
	nowarning 'citation.*undefined' ${MAINLOG} || touch ${REBIBFLAG}
	(test -f ${REBIBFLAG} && ${make} -k bibtex_doit latex_doit); echo BIB OK.
	@echo rerun if the post-latex ToC is not identical to the pre-latex one.
	diff ${MAINTOC} ${MAINTOC}.copy > /dev/null || ${make} latex_doit
	@echo check for log messages telling us to rerun
	nowarning 'rerun' ${MAINLOG} || ${make} latex_doit
	nowarning 'rerun' ${MAINLOG} || ${make} latex_doit
	nowarning 'warning' ${MAINLOG} || ${make} latex_doit
	@echo report success only if there are no warning messages in log
	nowarning 'warning' ${MAINLOG}

${MAINBBL}:	${BIBFILES}
	touch ${MAINBBL}
	touch ${REBIBFLAG}

latex_doit:
	touch ${MAINTOC} ; cp -p ${MAINTOC} ${MAINTOC}.copy
	$(latex) '\nonstopmode\input{${MAINFILE}}'

bibtex_doit:
	$(bibtex) ${MAIN}
	rm -f ${REBIBFLAG}

%.eps : %.fig
	$(fig2dev) -L ps -p portrait $< $@

%.ps : %.dvi
	dvips -o $@ $<

