################################################################################
# Makefile for vorlage.tex                                                     #
# (C) Uwe Domaratius 2006-2007                                                 #
# additional bash magic by Martin Fiedler                                      #
################################################################################

## define useful variables, change these if necessary
DA       = vorlage
BIB      = literatur.bib

## define paths to the required programs
BIBTEX   = bibtex
DVIPS    = dvips
LATEX    = latex
MAKEIDX  = makeindex
PDFLATEX = pdflatex
SED      = sed
GAWK     = gawk
GREP     = grep
TOUCH    = touch
GS       = gs
EPSTOPDF = epstopdf
CONVERT  = convert
FIG2DEV  = fig2dev
PLOT     = gnuplot
INKSCAPE = inkscape

## define output as /dev/null to suppress all program output
OUT      = /dev/null

## Required programs (as listing for make progs)
REQUIRED = $(BIBTEX) $(CONVERT) $(DVIPS) $(EPSTOPDF) $(FIG2DEV) $(PLOT) $(GS) $(INKSCAPE) $(LATEX) $(MAKEIDX) $(PDFLATEX)

## define additional directories
# bitmap pics as jpg, png or pdf in /pics
# vector graphics as fig or svg in /figs
# gnuplot files as plt in /plots
PICDIR   = ./pics
FIGDIR   = ./figs
PLTDIR   = ./plots

## defining sourcefiles and other latex-stuff (you'd better not touch anything but TEXFILES, like for additional include directories)
## bash magic for shell command by Martin Fiedler
TEXFILES = $(wildcard *.tex)
TEXSTY = $(TEXFILES) user.sty
CLASS = $(addsuffix .cls,$(shell sed -n -e '/\\documentclass/,/}/p' $(DA).tex | tr -d '\r' | tr -d '\t' | sed -r 's/%.*//;s/ //g' | tr -d '\n' | sed -r 's/.*\{//;s/\}//'))
PACKAGES = $(filter-out user.sty,$(addsuffix .sty,$(shell for p in $(TEXSTY) ; do grep -i -s '[^% ].*usepackage\|RequirePackage' $$p | sed 's/.*usepackage.*{\([^}]*\).*/\1/;s/.*[Rr]equire[Pp]ackage.*{\([^}]*\).*/\1/' ; done | sort | uniq)))

## get all graphics files that are supported in some way or another
PDFPICS = $(wildcard $(PICDIR)/*.pdf)
EPSPICS = $(wildcard $(PICDIR)/*.eps)
JPGPICS = $(wildcard $(PICDIR)/*.jpg)
PNGPICS = $(wildcard $(PICDIR)/*.png)
FIGFIGS = $(wildcard $(FIGDIR)/*.fig)
EPSFIGS = $(wildcard $(FIGDIR)/*.eps)
PDFFIGS = $(wildcard $(FIGDIR)/*.pdf)
SVGFIGS = $(wildcard $(FIGDIR)/*.svg)
PLOTS   = $(wildcard $(PLTDIR)/*.plt)

# define data for logos used on title page
LOGOS   = logo_english.eps logo_english.pdf logo_deutsch.eps logo_deutsch.pdf

###############################################################################
## No editing below here should be necessary!

# get all files that need to be converted into eps
# only include those files that do not have a corresponding file in eps or pdf
# to avoid circular dependencies
EPSFROMPDF = $(filter-out $(EPSPICS),$(patsubst %.pdf,%.eps,${PDFPICS}))
PDFFROMEPS = $(filter-out $(PDFPICS) $(patsubst %.jpg,%.pdf,${JPGPICS}) $(patsubst %.png,%.pdf,${PNGPICS}), $(patsubst %.eps,%.pdf,${EPSPICS}))
EPSFROMJPG = $(filter-out $(EPSPICS),$(patsubst %.jpg,%.eps,${JPGPICS}))
EPSFROMPNG = $(patsubst %.png,%.eps,${PNGPICS})
EPSFROMFIG = $(patsubst %.fig,%.eps,${FIGFIGS})
PDFFROMFIG = $(patsubst %.fig,%.pdf,${FIGFIGS})
EPSFROMSVG = $(filter-out $(EPSFIGS),$(patsubst %.svg,%.eps, ${SVGFIGS}))
PDFFROMSVG = $(filter-out $(PDFFIGS),$(patsubst %.svg,%.pdf, ${SVGFIGS}))
EPSFROMPLT = $(patsubst %.plt,%.eps,${PLOTS})
PDFFROMPLT = $(patsubst %.plt,%.pdf,${PLOTS})

## Logfile messages to grep for
RERUN    = "^LaTeX Warning: .* Rerun to get"
WARNING  = "^LaTeX Warning: "
NOFILE   = "^No file "
OVERFULL = "^Overfull "
UNDERFULL= "^Underfull "
ERROR    = "^! "

## First make target: a syntax help to be shown when calling make without params
help:
	@echo " Makefile for compiling vorlage.tex to DVI, PostScript and PDF"
	@echo ""
	@echo " Possible targets:"
	@echo "   make dvi      -- creates DVI output"
	@echo "   make ps       -- creates PS file from DVI output"
	@echo "   make pdf      -- uses pdflatex to create PDF"
	@echo "   make pictures -- convert everything in /pics to useful formats"
	@echo "   make figures  -- convert everything in /figs to useful formats"
	@echo "   make plots    -- converts all Gnuplot plt to images"
	@echo "   make clean    -- deletes all intermediate files"
	@echo "   make mrproper -- deletes everything but the source files"
	@echo ""
	@echo "   make verbose  -- just calls latex (for debugging purposes)"
	@echo "   make check    -- calls latex and shows only warnings and errors"
	@echo "   make progs    -- checks whether all required programs are present"
	@echo "   make show-pkg -- shows which LaTeX packages are included via \usepackage"
	@echo "   make chk-pkg  -- checks whether necessary .sty files are available"
	@echo " Get more help by adding -help to make target, e.g. make pdf-help"

## additional help-targets
dvi-help:
	@echo "  Help for 'make dvi'"
	@echo "  'make dvi' sets the document and produces output in DVI format. The necessary"
	@echo "  calls to BibTeX and Makeindex are all managed automatically. If pictures in a"
	@echo "  non-usable are found in the subdirectory '/pics', a conversion is done. Same"
	@echo "  goes for vector graphics in '/figs' and Gnuplot scripts in '/plots'."
	@echo ""
	@echo "  Related help topics: pictures-help, figures-help, plots-help"

ps-help:
	@echo " Help for 'make ps'"
	@echo " 'make ps' typesets the document as DVI and converts the resulting file into PS"
	@echo " using dvips."
	@echo ""
	@echo " Related help topics: dvi-help"

pdf-help:
	@echo " Help for 'make pdf'"
	@echo " 'make pdf' works in the same way as 'make dvi', but uses pdflatex to produce"
	@echo " PDF output."
	@echo ""
	@echo " Related help topics: dvi-help"

pictures-help:
	@echo " Help for 'make pictures'"
	@echo " 'make pictures' goes through the subdirectory defined as PICDIR and looks for"
	@echo " all files in the formats EPS, JPG, PNG, and PDF. The following conversions"
	@echo " are done: EPS -> PDF, JPG -> EPS, PNG -> EPS, PDF -> EPS"
	@echo " Only source files that do not have an equivalent in the destination format"
	@echo " are converted."
	@echo " Programs used for conversion:"
	@echo "   EPS->PDF: epstopdf"
	@echo "   JPG->EPS, PNG->EPS: convert (ImageMagick)"
	@echo "   PDF->EPS: gs (GhostScript)"

figures-help:
	@echo " Help for 'make figures'"
	@echo " 'make figures' goes through the subdirectory defined as FIGDIR and looks for"
	@echo " all files in the formats FIG and SVG. These are converted to both eps and"
	@echo " pdf, but only if these converted files do not already exist."
	@echo " Programs used for conversion:"
	@echo "   FIG->EPS, FIG->PDF: fig2dev (transfig package)"
	@echo "   SVG->EPS: inkscape
	@echo "   SVG->EPS->PDF: epstopdf"

plots-help:
	@echo " Help for 'make plots'"
	@echo " 'make plots' goes through the subdirectory defined as PLOTS and looks for"
	@echo " Gnuplot skript files ending on PLT. These files are plotted and exported"
	@echo " to EPS and PDF."
	@echo " Important note: The PLT file must not set any terminal or output, otherwise"
	@echo " the export will fail!"

clean-help:
	@echo " Help for 'make clean'"
	@echo " 'make clean' removes all files that are created as intermediate results by"
	@echo " latex, bibtex and makeindex."
	@echo " Converted pictures, figures and plots are not touched."

mrproper-help:
	@echo " Help for 'make mrproper'"
	@echo " 'make mrproper' calls 'make clean' and additionally removes the DVI, PS and"
	@echo " PDF result files. No other files or subdirectories are touched."
	@echo ""
	@echo " Related help topics: clean-help"

verbose-help:
	@echo " Help for 'make verbose'"
	@echo " 'make verbose' just calls latex to process the document. The same effect"
	@echo " could be achieved by typing 'latex vorlage.tex'."
	@echo " This make target is mainly intended for debugging."
	@echo ""
	@echo " Related help topics: check-help"

check-help:
	@echo " Help for 'make check'"
	@echo " 'make check' is intended for debugging purposes. It calls latex to process"
	@echo " the document. After processing the document, the logfile is checked for"
	@echo " errors, warnings, missing files and over/underfull boxes. Only these log"
	@echo " messages are displayed."
	@echo " If an error is found, 'make verbose' could by used to find out what causes"
	@echo " the error."
	@echo ""
	@echo " Related help topics: verbose-help"

progs-help:
	@echo " Help for 'make progs'"
	@echo " 'make progs' goes through the program list given at the beginning of the"
	@echo " makefile and checks whether these programs can be found. If other programs"
	@echo " are available which can replace a program given here, the makefile needs"
	@echo " to be changed accordingly."

show-pkg-help:
	@echo " Help for 'make show-pkg'"
	@echo " 'make show-pkg' shows a list of all latex packages that are necessary to"
	@echo " process the document. Note that some of these packages are part of bigger"
	@echo " packages including several style files."
	@echo " A list of packages used to create the document is given in an appendix of the"
	@echo " document."

chk-pkg-help:
	@echo " Help for 'make chk-pkg'"
	@echo " 'make chk-pkg' tries to locate the .sty files used by the TeX sources. Note"
	@echo " that you need to have a filename database that locate can use. Also note that"
	@echo " locate only shows the location of the files, not whether these files are actually"
	@echo " the correct ones to be used."

################################################################################
## make targets in understandable format
# create pdf
pdf: $(DA).pdf

# create dvi
dvi: $(DA).dvi

# create ps
ps: $(DA).ps

# debugging call to latex, showing all output which is otherwise suppressed
verbose:
	@$(LATEX) $(DA)

# parse sourcefiles and only show erros, warnings and over/underfull boxes
check:
	@echo "checking source file(s)..."
	@$(LATEX) -interaction=nonstopmode $(DA) >$(OUT); true
	@grep $(ERROR) $(DA).log; true
	@grep $(WARNING) $(DA).log; true
	@grep $(NOFILE) $(DA).log; true
	@grep $(OVERFULL) $(DA).log; true
	@grep $(UNDERFULL) $(DA).log; true

# check whether all necessary programs are available and can be found
progs:
	@for p in $(REQUIRED); do \
		loc=`which $$p 2>$(OUT)`; \
		if [ "$$?" = "0" ]; then echo "$$loc ... OK"; \
		else echo "$$p: ERROR!";\
		fi; \
	done;

# show latex packages and documentclass, may need some better formatting
# list all packages referenced via \usepackage, ignoring those commented out
## bash magic by Martin Fiedler
show-pkg:
	@echo "Documentclass used: "
	@sed -n -e '/\\documentclass/,/}/p' $(DA).tex | tr -d '\r' | tr -d '\t' | sed -r 's/%.*//;s/ //g;s/,/, /g' | tr -d '\n' | fold -s --width 79
	@echo
	@echo "Packages loaded via \usepackage: "
	@echo $(PACKAGES) | sed 's/.sty//g;s/ /, /g' | fold -s --width=79
	@echo

chk-pkg:
	@loc=`locate $(CLASS)`>$(OUT); \
	if [ "$$?" = "0" ]; then echo "$$loc ... OK" | sed -r 's/.*\/l?a?tex\///'; \
	else echo "$(CLASS) ... ERROR"; fi;
	@for p in $(PACKAGES); do \
		loc=`locate */$$p`>$(OUT); \
		if [ "$$?" = "0" ]; then echo "$$loc ... OK" | sed -r 's/.*\/l?a?tex\///'; \
		else echo "$$p not found!"; \
		fi; \
	done;
	@echo

################################################################################
## targets as filenames

# creation of pdf depends on existence of bibliography file (bbl), index (ind), 
# acronym list (acn) and glossary (gls)
# if all these files are up to date, pdflatex is run, the logfile is checked 
# for changed labels and pdflatex is rerun if necessary
# the final touch to the required files prevents reworking all of them if 
# make dvi/pdf/ps is called again

$(DA).pdf: $(DA).bbl $(DA).ind $(DA).acn $(DA).gls $(PDFFROMEPS) $(PDFFROMFIG) \
$(PDFFROMSVG) $(PDFFROMPLT)
	@echo "Running pdfLaTeX..."
	@$(PDFLATEX) $(DA) >$(OUT)
	@while grep $(RERUN) $(DA).log >$(OUT); do \
		echo "pdfLaTeX needs to be run again..."; $(PDFLATEX) $(DA) >$(OUT); \
	done
	@echo "PDF creation finished!"
	@touch $(DA).bbl $(DA).ind $(DA).acn $(DA).gls $(DA).pdf

# creation of dvi depends on existence of bibliography file (bbl), index (ind), 
# acronym list (acn) and glossary (gls)
# if all these files are up to date, latex is run, the logfile is checked 
# for changed labels and latex is rerun if necessary
# the final touch to the required files prevents reworking all of them if 
# make dvi/pdf/ps is called again

$(DA).dvi: $(DA).bbl $(DA).ind $(DA).acn $(DA).gls
	@echo "Running LaTeX..."
	@$(LATEX) $(DA) >$(OUT)
	@while grep $(RERUN) $(DA).log >$(OUT); do \
		echo "LaTeX needs to be run again..."; $(LATEX) $(DA) >$(OUT); \
	done
	@echo "DVI creation finished!"
	@touch $(DA).bbl $(DA).ind $(DA).acn $(DA).gls $(DA).dvi


# creation of ps file only depends on the existence of the dvi which is 
# converted using dvips
$(DA).ps: $(DA).dvi
	@echo "Running dvips..."
	@dvips -q $(DA) >$(OUT)
	@echo "PS creation finished!"

################################################################################
## intermediate targets to get the dependencies

# Bibliography file, depending on the literature database and the auxiliary
# file. Bibliography is simply created by running BibTeX

$(DA).bbl bibtex: $(DA).aux $(BIB)
	@echo "Running BibTeX..."
	@$(BIBTEX) $(DA) >$(OUT)

# The files for acronyms, glossary and index depend on files that are created
# during the first run of LaTeX. The corresponding files are created by running
# makeindex

# acronyms
$(DA).acn acronym: $(DA).acr
	@echo "Creating list of acronyms..."
	@$(MAKEIDX) -q -s $(DA).ist -t $(DA).alg -o $(DA).acn $(DA).acr >$(OUT)

# glossary
$(DA).gls glossary: $(DA).glo
	@echo "Creating glossary..."
	@$(MAKEIDX) -q -s $(DA).ist -t $(DA).glg -o $(DA).gls $(DA).glo >$(OUT)

# index
$(DA).ind index: $(DA).idx
	@echo "Creating index file..."
	@$(MAKEIDX) -q $(DA) >$(OUT)

# The most basic auxiliary files that need to be created for all subsequent 
# runs. These only depend on the source tex files.

$(DA).aux $(DA).idx $(DA).acr $(DA).glo: $(TEXFILES) $(LOGOS) $(EPSFROMJPG) $(EPSFROMPDF)\
$(EPSFROMPNG) $(EPSFROMFIG) $(EPSFROMSVG) $(EPSFROMPLT)
	@echo "Creating auxiliary files..."
	@-$(LATEX) -interaction=nonstopmode $(DA) >$(OUT)
	@if grep $(ERROR) $(DA).log >$(OUT); then \
		echo "There were errors. Check your source files and try 'make verbose' to find the problem."; \
	else while grep $(RERUN) $(DA).log >$(OUT); do \
		echo "LaTeX needs to be run again..."; $(LATEX) $(DA) >$(OUT); \
	done; fi;
	@touch $(DA).idx

pictures: $(EPSFROMJPG) $(EPSFROMPDF) $(EPSFROMPNG) $(PDFFROMEPS)

figures: $(EPSFROMFIG) $(PDFFROMFIG) $(EPSFROMSVG) $(PDFFROMSVG)

plots: $(EPSFROMPLT) $(PDFFROMPLT)

$(EPSFROMPDF): %.eps : %.pdf
	@echo "Converting $< to $@..."
	@$(GS) -sDEVICE=epswrite -sOutputFile=$@ -r96 -dNOPAUSE -dBATCH $< >$(OUT)

$(EPSFROMPNG): %.eps : %.png
	@echo "Converting $< to $@..."
	@$(CONVERT) -compress Zip $< eps3:$@
	@touch $< $@

$(EPSFROMJPG): %.eps : %.jpg
	@echo "Converting $< to $@..."
	@$(CONVERT) -compress Zip $< eps3:$@
	@touch $< $@

$(PDFFROMEPS): %.pdf : %.eps
	@echo "Converting $< to $@..."
	@epstopdf $<

$(EPSFROMFIG): %.eps : %.fig
	@echo "Converting $< to $@..."
	@$(FIG2DEV) -L eps $< > $@

$(PDFFROMFIG): %.pdf : %.fig
	@echo "Converting $< to $@..."
	@$(FIG2DEV) -L pdf $< > $@

$(EPSFROMSVG): %.eps : %.svg
	@echo "Converting $< to $@..."
	@$(INKSCAPE) -z -file=$< --export-eps=$@

$(PDFFROMSVG): %.pdf : %.eps
	@echo "Converting $< to $@..."
	@$(EPSTOPDF) $<

$(EPSFROMPLT): %.eps : %.plt
	@echo "Converting $< to $@..."
	@echo "set terminal postscript eps enhanced color solid" >helper.plot
	@echo "set output '$@'" >>helper.plot
	@$(PLOT) helper.plot $<
	@rm -f helper.plot

$(PDFFROMPLT): %.pdf : %.plt
	@echo "Converting $< to $@..."
	@echo "set terminal pdf enhanced" >helper.plot
	@echo "set output '$@'" >>helper.plot
	@$(PLOT) helper.plot $<
	@rm -f helper.plot
	
################################################################################
## targets to clean up after operation

# simple deletion of all intermediate files
clean:
	@echo "Throwing intermediate files away..."
	@rm -f *.acn *.alg *.aux *.bbl *.blg *.ent *.glg *.glo *.gls *.idx *.ilg \
	       *.ind *.ist *.loa *.lof *.log *.lot *.mpx *.out *.toc *.acr *.tpt *.thm

# in addition, one can remove everything but the source files
mrproper: clean
	@echo "Removing result files, leaving only source files..."
	@rm -f $(DA).ps $(DA).pdf $(DA).dvi