EXERCISES=$(TEXFILES:.tex=.pdf)
SOLUTIONS=$(EXERCISES:%.pdf=%-solutions.pdf)

.PHONY: pdf exercises solutions watch watchexercises watchsolutions clean

pdf : $(SOLUTIONS) $(EXERCISES)

exercises : $(EXERCISES)

solutions : $(SOLUTIONS)

$(SOLUTIONS) : %-solutions.pdf : %.tex ../../exercisesheader.tex ../../exercisestitle.tex
	{ echo "\\documentclass[answers,12pt,a4paper,pdftex]{exam}"; sed -e '1d' $<; } > $(patsubst %.pdf,%.tex,$@)
	pdflatex -interaction=scrollmode $(patsubst %.pdf,%.tex,$@) | tee /dev/stderr | fgrep -q "Rerun to get cross-references right" && pdflatex -interaction=scrollmode $(patsubst %.pdf,%.tex,$@) || true
	rm $(patsubst %.pdf,%,$@).[!p]*

$(EXERCISES) : %.pdf : %.tex ../../exercisesheader.tex ../../exercisestitle.tex
	pdflatex -interaction=scrollmode $< | tee /dev/stderr | fgrep -q "Rerun to get cross-references right" && pdflatex -interaction=scrollmode $< || true

watch :
	while true; do ! make -q pdf && make pdf; sleep 0.5; done

watchexercises :
	while true; do ! make -q exercises && make exercises; sleep 0.5; done

watchsolutions :
	while true; do ! make -q solutions && make solutions; sleep 0.5; done

clean :
	rm -f *~ *.aux *.log *.out

cleanup : clean
	rm -f $(SOLUTIONS) $(EXERCISES)