PROJECTNAME=$(basename $(wildcard *.tex))
LIBS=$(notdir $(wildcard libs/*))
FIGS=$(notdir $(wildcard figs/*.fig))
PICS=$(notdir $(wildcard figs/*.jpg))

PDFS=$(addsuffix .pdf, $(PROJECTNAME))
SYNCTEXS=$(addsuffix .synctex.gz, $(PROJECTNAME))

all: $(PROJECTNAME)

$(PROJECTNAME): $(LIBS) $(FIGS) $(PICS)
	pdflatex -file-line-error $@.tex
	pdflatex -synctex=1 $@.tex

$(PROJECTNAME).aux: $(LIBS) $(FIGS) $(PICS)
	pdflatex -file-line-error -draftmode $(PROJECTNAME).tex


$(SYNCTEXS): $(LIBS) $(FIGS) $(PICS)
	pdflatex -synctex=1 $(patsubst %.synctex.gz, %.tex, $@)


libs: $(LIBS)

$(LIBS):
	ln -fs libs/$@ ./

figs: $(FIGS)

$(FIGS):
	make -C figs/$@
	for pdf in $$(find figs/$@/ -name '*.pdf'); do ln -fs "$$pdf" ./ ; done
	for png in $$(find figs/$@/ -name '*.png'); do ln -fs "$$png" ./ ; done

$(PICS):
	ln -fs figs/$@ ./

clean-aux: clean-figs-aux
	rm -f $(addsuffix .aux, $(PROJECTNAME))
	rm -f $(addsuffix .log, $(PROJECTNAME))
	rm -f $(addsuffix .out, $(PROJECTNAME))
	rm -f $(addsuffix .toc, $(PROJECTNAME))

clean-libs:
	rm -f $(LIBS)

clean-figs:
	$(foreach fig,$(addprefix figs/, $(FIGS)), make -C $(fig) clean; )
	rm -f $(notdir $(wildcard figs/*.fig/*.pdf))
	rm -f $(notdir $(wildcard figs/*.fig/*.png))
	rm -f $(PICS)

clean-figs-aux:
	$(foreach fig,$(addprefix figs/, $(FIGS)), make -C $(fig) clean-aux; )


clean-tex:
	rm -f $(PDFS) $(SYNCTEXS)

clean: clean-aux clean-tex clean-libs clean-figs
