ifndef SRCNAMES
    SRCNAMES = $(shell grep -l "^[^%]*{document}" *.tex)
endif

ifdef SRCNAME
	SRCNAMES := $(SRCNAME).tex
endif

ifeq ($(words $SRCNAMES), 1)
	SRCNAME = $(SRCNAMES)
endif

PDFNAMES = $(foreach FILE, $(SRCNAMES:.tex=.pdf), $(FILE))
DVINAMES = $(foreach FILE, $(SRCNAMES:.tex=.dvi), $(FILE))
BBLNAMES = $(foreach FILE, $(wildcard *.aux), $(FILE:.aux=.bbl))

$(warning SRCNAMES: $(SRCNAMES))
$(warning PDFNAMES: $(PDFNAMES))
#$(warning BBLNAMES: $(BBLNAMES))
#$(warning SRCNAME: $(SRCNAME))

# The resource file for bibtool
BIBRCNAME = bibtool.rc

# Calculate the path to the current dir when run recursively
THISDIR = $(dir $(lastword $(MAKEFILE_LIST)))

export TEXINPUTS:=${TEXINPUTS};$(THISDIR)//;$(THISDIR)/Corporate/4-3

BIBSRC	=	$(wildcard *.bib)
TEXSRC	=	$(wildcard *.tex)

#-- Software Environment Setup -------------------------------
SHELL	= /bin/bash
LATEX	= latex -src
BIBTEX	= bibtex
DVIPS	= dvips
PDFPS	= pdftops
PDF	= max_print_line=1000 pdflatex -shell-escape -src -halt-on-error -synctex=1 -interaction nonstopmode -file-line-error-style
OPEN    = xdg-open
MD5SUM  = md5sum

# Mac-specific definitions
ifeq ($(shell uname), Darwin)
    OPEN=open
endif

.PHONY: default
default: pdf				# Default goal

.PHONY: dvi
dvi : $(DVINAMES) 			# Compile dvi's

.PHONY: pdf
pdf : $(PDFNAMES) 			# Compile pdf's

.PHONY: over
over : clean pdf			# Force recompile

.PHONY: clean
clean :
	@echo Soft clean
	-rm *.blg *.log *.out $(DVINAMES) $(PDFNAMES) 2>/dev/null ; true

.PHONY: cleanall
cleanall : clean
	@echo Hard clean
	-rm *~ *.aux *.bbl *.lof *.lot *.toc *.ps *.cit *.synctex.gz *.run.xml *.bcf 2>/dev/null ; true

.PHONY: cleanaux
cleanaux :
	-rm *.blg *.log *.out *.dvi*.aux *.bbl *.lof *.lot *.toc *.ps *.cit *.synctex.gz 2>/dev/null ; true

.PHONY: show
show: $(PDFNAMES)
	for file in $(PDFNAMES); do $(OPEN) $$file; done

.PHONY: edit
edit: $(SRCNAMES)
	for file in $(SRCNAMES); do $(OPEN) $$file; done

%.bbl: $(BIBSRC)
#	@echo Recreate the .aux file
#	$(PDF) $(@:.bbl=.tex) >/dev/null || cat $(@:.bbl=.log)

	@echo Recreate the .bbl file
	$(BIBTEX) $(@:.bbl=.aux) | true

	@echo Flush the citation hash
	test -s $(@:.pdf=.cit) || echo '' | $(MD5SUM) > $(@:.pdf=.cit)

%.aux : %.pdf;

%.dvi: %.tex	# Cancel the default rule

%.dvi: $(TEXSRC) $(wildcard $(THISDIR)*.tex)
	@echo If compilation fails manipuate the timestamp to prevent recognission of .dvi as ready
	$(LATEX) $(@:.dvi=.tex) || (touch --date="`date -R -r $(@:.dvi=.tex)`" $@ & false)

	@echo If the citations were updated recompile the .bbl file
	grep -o -G "Citation \`[^']*" $(@:.dvi=.log) | $(MD5SUM) -c --status $(@:.dvi=.cit) || $(BIBTEX) $(@:.dvi=.aux)

	while grep -q "Rerun to get cross-references right." $(@:.dvi=.log); \
	do $(LATEX) $(@:.dvi=.tex); done

	@echo Update the missing citation hash
	grep -o -G "Citation \`[^']*" $(@:.dvi=.log) | $(MD5SUM) > $(@:.dvi=.cit)

%.pdf: %.tex	# Cancel the default rule

%.pdf: $(TEXSRC) $(wildcard $(THISDIR)*.tex) $(BBLNAMES)
	@echo Compiling $@
	($(PDF) $(@:.pdf=.tex)) || (touch --date="`date -R -r $(@:.pdf=.tex)`" $@ & rm -f $(@:.pdf=.aux) & grep "Warning" $(@:.pdf=.log))


	@echo Recompile tikz images
	@if [ -s $(@:.pdf=.makefile) ]; \
	then \
	    $(MAKE) -e -f $(@:.pdf=.makefile); \
	    $(PDF) $(@:.pdf=.tex) >/dev/null;  \
	fi

	@echo Create $(@:.pdf=.cit) if it does not exist
	test -s $(@:.pdf=.cit) || echo '' | $(MD5SUM) > $(@:.pdf=.cit)

	@echo If the citations were updated recompile the .bbl file
	grep -o -G "Citation \`[^']*" $(@:.pdf=.log) | $(MD5SUM) -c --status $(@:.pdf=.cit) || rm -f *.bbl; $(MAKE) bibtex; $(PDF) $(@:.pdf=.tex) >/dev/null

	@echo -n "Search for dangling references.. "
	@if grep -q "Rerun to get cross-references right." $(@:.pdf=.log); \
	then \
	    echo "Run LaTeX twice no matter how silly it is" \
	    $(PDF) $(@:.pdf=.tex) >/dev/null; \
	    $(PDF) $(@:.pdf=.tex) >/dev/null; \
	else \
	    echo "None"; \
	fi

	@echo Update the citation hash
	grep -o -G "Citation \`[^']*" $(@:.pdf=.log) | $(MD5SUM) > $(@:.pdf=.cit)

%.ps : %.pdf
	$(PDFPS) -level1 $<  		# Create .ps from .pdf

.PHONY: bib
bib:  bibtex

.PHONY: bibtool
bibtool: $(BIBSRC)
	#Normalise all bibfiles
	for bf in $(BIBSRC); do \
               bibtool -s -v -i $$bf -o $$bf -r $(THISDIR)/$(BIBRCNAME); \
        done

.PHONY: bibtex
bibtex: $(BBLNAMES)

.PHONY: pack
pack: $(TEXSRC)
	make cleanall
	$(MAKE) pdf
	mkdir -p submission
	# purging old files if any
	rm -Rf submission/*
	# copying all files from TexCommon mentioned in log-file
	for file in $(THISDIR)/*; do \
                 if grep --quiet $(shell basename $(THISDIR))/$$(basename $$file) *.log; \
                    then cp -v $$file submission; \
                 fi; done
	cp *.bib submission || echo "There are no bib-file!"
	cp *.bbl submission || echo "There are no bbl-file!"
	cp *.bst submission || echo "There are no bst-file!"
	# copying all files from the current directory mentioned in log-file
	for file in * ; do if [ -f $$file ]; then  (if grep --quiet $$file *.log; then cp $$file submission; fi); fi ; done
	# remove comments
	for file in submission/*.tex; do perl -i -pe 's/(^|[^\\])%.*/\1%/' $$file; done
	# remove appendix
	#for file in submission/*.tex; do sed -i '/\\appendix/,$$c \\\end{document}' $$file ; done
	for file in submission/*.tex; do sed -i '/\\\end{document}/q' $$file ; done
	cd submission; rm -f *.aux *.blg *.log *.out; rm -f ../submission.zip; zip -r ../submission.zip *

.PHONY: up
up: $(PDFNAMES)
	for fn in $(PDFNAMES); do rcp $$fn www8.informatik.uni-erlangen.de:/home/$(USER)/$$fn ; done
#	rcp $(SRCNAME).ps  www8.informatik.uni-erlangen.de:/home/$(USER)/$(EXTNAME).ps

# Check common text writting issues
.PHONY: check
check:
	@echo "Checking duplicates.."
	@grep -Eon -r --include "*.tex" '(\b[[:alpha:]]{2,}\b) \1\b' . | true
	@echo "Checking spelling.."
	cat $(SRCNAMES) | aspell --conf-dir=$(THISDIR) --home-dir=$(THISDIR) list -t --dont-tex-check-comments -d en_GB-ize | sort -uf | sed -E '/.../!d'
