TEXFILES=$(wildcard statistics??.tex)
EXERCISES=$(TEXFILES:.tex=.pdf)
SOLUTIONS=$(EXERCISES:statistics%=solutions%)

.PHONY: pdf exercises solutions watch watchexercises watchsolutions clean

pdf : $(SOLUTIONS) $(EXERCISES)

exercises : $(EXERCISES)

solutions : $(SOLUTIONS)

$(SOLUTIONS) : solutions%.pdf : statistics%.tex instructions.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 instructions.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)
