PDFDIR = PDF
CODEDIR = code
GNUPLOTDIR = gnuplot
BIBTEXDIR = bibtex
GNUPLOTLATEXDIR = gnuplot-latex
REPSDIR = r-eps
GNUPLOTSVGDIR = gnuplot-svg
GNUPLOTLATEXEPSDIR = $(GNUPLOTLATEXDIR)/eps
RM = rm -f
LATEX = latex -interaction=nonstopmode -shell-escape
DVIPS = dvips
PS2PDF = ps2pdf

all: pdf zip

zip: $(addprefix $(PDFDIR)/,$(patsubst   %.tex,%.zip, $(wildcard $(addsuffix .tex, $(addprefix *,$(subst DEMO,, $(wildcard DEMO-*)))))))

pdf: $(patsubst   %.tex,%.pdf,$(addprefix $(PDFDIR)/, $(wildcard   *-*.tex))) $(patsubst   %.tex,%.P, $(wildcard   *-*.tex))


$(PDFDIR)/%.pdf: %.tex %.P
	$(LATEX) $<
	@if(grep "Rerun" $*.log > /dev/null);\
		then \
		$(LATEX) $<;\
	fi
	rm -f $*.log
	$(DVIPS) $(shell basename $< .tex)
	$(PS2PDF) $(shell basename $< .tex).ps $@

$(CODEDIR)/%.eps: $(CODEDIR)/%.tex
	make -C $(CODEDIR) $(notdir $@)

$(REPSDIR)/%.eps: $(REPSDIR)/%.tex
	make -C $(REPSDIR) $(notdir $@)

$(BIBTEXDIR)/%.eps: $(BIBTEXDIR)/%.tex
	make -C $(BIBTEXDIR) $(notdir $@)

$(GNUPLOTDIR)/%.eps: $(GNUPLOTDIR)/%.gnuplot
	make -C $(GNUPLOTDIR) $(notdir $@)

$(GNUPLOTSVGDIR)/%.eps: $(GNUPLOTSVGDIR)/%.gnuplot
	make -C $(GNUPLOTSVGDIR) $(notdir $@)

$(GNUPLOTLATEXEPSDIR)/%.eps: $(GNUPLOTLATEXDIR)/%.gnuplot
	make -C $(GNUPLOTLATEXDIR) eps/$(notdir $@)


%.P : %.tex
# 	`perl -e 'print "$(PDFDIR)/$(shell basename $< .tex).pdf : "; while(<STDIN>) {if(/\\input\{(.*)\}/){  print "$$1 "}}' < $< > $@`
	`perl -e 'print "$(PDFDIR)/$(shell basename $< .tex).pdf : "; while(<STDIN>) {if($$_!~/^\%/ && /\\input\{(.*)\}/){ print "$$1 "; open FILE, "$$1"; while(my $$line=<FILE>) {if($$line!~/^\%/ && $$line=~/\\includegraphics(?:[^\{]*)\{([^\}]*)\}/) {print "$$1 "}}; close FILE; }}' < $< > $@`
	`perl -e 'print "\n$(shell basename $< .tex).P : "; while(<STDIN>) {if($$_!~/^\%/ && /\\input\{(.*)\}/){ print "$$1 "; open FILE, "$$1"; while(my $$line=<FILE>) {if($$line!~/^\%/ && $$line=~/\\includegraphics(?:[^\{]*)\{([^\}]*)\}/) {print "$$1 "}}; close FILE; }}' < $< >> $@`


.SECONDEXPANSION:
$(PDFDIR)/%.zip: $(PDFDIR)/%.pdf $$(addprefix DEMO-, $$(lastword $$(subst -, , $$**)))/*
	zip -j $@ $<
	zip -r $@ $(filter-out $<,$^) -x \*~ \*.backup


include $(wildcard *-*.P)


clean:
	$(RM) *.dvi *.ps* *~ *.out *.pdf *.log *.aux *.backup

cleanzip:
	$(RM) $(PDFDIR)/*.zip

