#!/bin/bash
#
# compile a feynman diagram

if [ $# -eq 1 ]; then
    echo "Building $1_diagram from $1.tex"
else 
    echo "Usage: bash make_plot.sh texfileName"
    echo "texfileName is without .tex!"
    exit 2
fi

pdflatex $1".tex"  2>/dev/null 1>&2
if [ $? -ne 0 ]; then
    echo "First compilation failed. Check log."
    exit 1
else 
    echo "First pdflatex succesfully completed."
fi

mpost $1"_diagram"  2>/dev/null 1>&2
if [ $? -ne 0 ]; then
    echo "mpost compilation failed. Check log."
    exit 1
else 
    echo "mpost succesfully completed."    
fi

pdflatex $1".tex"  2>/dev/null 1>&2
if [ $? -ne 0 ]; then
    echo "Second compilation failed. Check log."
    exit 1
else 
    echo "Second pdflatex succesfully completed."
fi

#Remove the second pdf page, pdftk need output != input so rename it afterwards
#If it works, it aint stupid
pdftk $1.pdf cat 1 output $1_2.pdf 
mv $1_2.pdf $1.pdf 

#Always clean after build
rm $1.aux
rm $1.log
rm $1.synctex
rm $1_diagram.log
rm $1_diagram.mp
rm $1_diagram.t1
rm $1_diagram.1


