TEX=platex
TEXFLAGS=
DVIPS=dvips -P cmz -t a4
DVIPDF=dvipdfmx -p a4
BIB = bibtex
BIBFLAGS =
TEXFILES = $(shell find . -name \*.tex)
RERUNTEX ="(There were undefined references|Rerun to get (cross-references|the bars) right)"
RERUNBIB ="No file.*\.bbl|Citation.*undefined"
COPY = if test -r $*.toc; then cp $*.toc $*.toc.bak; fi

.PHONY: all clean ps dvi pdf


all : pdf

pdf : main.dvi
	$(DVIPDF) main.dvi

ps : main.dvi
	$(DVIPS) main.dvi

dvi : main.dvi


main.dvi : main.tex $(TEXFILES) 
	@$(COPY); $(TEX) $(TEXFLAGS) $< 
	@(egrep -c $(RERUNBIB) $*.log > /dev/null) \
	  && ($(BIB) $(BIBFLAGS) $* && $(COPY); $(TEX) $(TEXFLAGS) $<); true
	@(egrep -c $(RERUNTEX) $*.log > /dev/null) \
	  && ($(COPY); $(TEX) $(TEXFLAGS) $<); true
	@(egrep -c $(RERUNTEX) $*.log > /dev/null) \
	  && ($(COPY); $(TEX) $(TEXFLAGS) $<); true
	@(egrep -c $(RERUNTEX) $*.log > /dev/null) \
	  && ($(COPY); $(TEX) $(TEXFLAGS) $<); true
	@if cmp -s $*.toc $*.toc.bak; \
	  then true; \
	  else $(TEX) $(TEXFLAGS) $<; fi
	@rm -f $*.toc.bak

clean:
	rm -f main.dvi main.ps *.aux *.log *.toc main.pdf \
	  *.bbl *.blg *.zip

