.PHONY: all clean show-errors show-log watch help

# Journal submissions compile with pdflatex (the publisher norm) + bibtex.
TEXFILE ?= main.tex
PROJECT  = $(basename $(TEXFILE))
LATEXMK  = latexmk
OUTDIR   = build
# Let bibtex find .bst/.bib regardless of latexmk's build/ run dir
# (Springer ships its styles under bst/).
export BSTINPUTS := $(CURDIR):$(CURDIR)/bst:
export BIBINPUTS := $(CURDIR):
MAKELOG  = $(OUTDIR)/make.log
TEXLOG   = $(OUTDIR)/$(PROJECT).log
ARTIFACTS = $(PROJECT).aux $(PROJECT).bbl $(PROJECT).blg $(PROJECT).log $(PROJECT).out \
	$(PROJECT).toc $(PROJECT).synctex.gz $(PROJECT).fls $(PROJECT).fdb_latexmk $(PROJECT).spl

all:
	@mkdir -p $(OUTDIR)
	@echo "Compiling $(PROJECT).tex (pdflatex, full log: $(MAKELOG))..."
	@$(LATEXMK) -pdf -outdir=$(OUTDIR) -interaction=nonstopmode $(PROJECT).tex < /dev/null > $(MAKELOG) 2>&1; \
	status=$$?; \
	if [ $$status -ne 0 ]; then \
		echo "Build failed."; \
		$(MAKE) -s show-errors; \
		echo "Full log: $(MAKELOG)"; \
		exit $$status; \
	fi
	@cp $(OUTDIR)/$(PROJECT).pdf ./$(PROJECT).pdf
	@rm -f $(ARTIFACTS)
	@echo "Done: $(PROJECT).pdf"

show-errors:
	@if [ -f $(TEXLOG) ]; then \
		grep -E -A2 '^! |^l\.[0-9]+ |LaTeX Error|Undefined control sequence|Missing \$$ inserted|Package .* Error|Emergency stop|Fatal error' \
			$(TEXLOG) 2>/dev/null \
			|| tail -30 $(MAKELOG); \
	else \
		tail -30 $(MAKELOG); \
	fi

show-log:
	@less $(MAKELOG)

watch:
	$(LATEXMK) -pvc -pdf -outdir=$(OUTDIR) -interaction=nonstopmode $(PROJECT).tex

clean:
	$(LATEXMK) -C -outdir=$(OUTDIR) $(PROJECT).tex
	rm -rf $(OUTDIR)
	rm -f $(ARTIFACTS)

help:
	@echo
	@echo '1. "make"            compile (pdflatex+bibtex via latexmk, PDF copied to root)'
	@echo '2. "make show-errors" re-print the error lines from the last build'
	@echo '3. "make show-log"   page through the full build log'
	@echo '4. "make watch"      continuous preview-compile'
	@echo '5. "make clean"      remove build/ and stray artifacts'
	@echo
