# Makefile for latex documents.

# Author: Mark George <mgeorge@infoscience.otago.ac.nz>

# driver file (tries to automatically find the driver file)
SOURCE=$(basename $(or $(wildcard lab*.tex), $(wildcard test*.tex), $(wildcard outline.tex), $(wildcard project*.tex),$(wildcard *exercises.tex),$(wildcard *report.tex),$(wildcard phase*.tex),$(wildcard lec*.tex)))
# if the driver file isn't one of the above then just set the value of the SOURCE variable to the name WITHOUT the extension


# preamble file
PREAMBLE=preamble

# files that will be deleted when we clean
RUBBISH=*.aux *.out *.dvi *.log *.ps *~ *.*~ auto *.toc *.fdb_latexmk *.fls

# latex command
LATEX=pdflatex

.PHONY:	clean

default: texify clean-rubbish

pdf: default

2up: pdf
	# spit out a 2up driver
	echo "\documentclass{article}\usepackage{pdfpages}\usepackage[a4paper,landscape, pdftex,vmargin=0in,hmargin=0.0in]{geometry}\begin{document}\includepdf[nup=2x1,frame,pages=-,delta=0mm 0mm]{%" >| 2up.tex
	echo ${SOURCE}.pdf% >> 2up.tex
	echo "}\end{document}" >> 2up.tex

	# texify it
	${LATEX} 2up.tex

	# clean up
	rm 2up.tex
	mv 2up.pdf ${SOURCE}_2up.pdf

	# get rid of any additional generated rubbish
	rm -rf $(RUBBISH)

# texify target
texify: ${SOURCE}.pdf

# compile as many times as needed (at least twice to get PDF bookmarks right) to sort out references and labels
${SOURCE}.pdf: ${SOURCE}.tex ${PREAMBLE}.tex
	$(LATEX) ${SOURCE}.tex
	$(LATEX) ${SOURCE}.tex

	# once more if there are still undefined references
	if [ -n "$(shell grep 'There were undefined references' ${SOURCE}.log)" ]; then $(LATEX) ${SOURCE}.tex ; fi

	# once more if there are labels that have changed
	if [ -n "$(shell grep 'Label(s) may have changed' ${SOURCE}.log)" ]; then $(LATEX) ${SOURCE}.tex ; fi

# delete unwanted generated files
clean-rubbish:
	rm -rf $(RUBBISH)

# delete ALL generated files
clean: clean-rubbish
	rm -rf ${SOURCE}.pdf ${SOURCE}_2up.pdf

