#!/bin/zsh

# Engine by Dan Drake

# Note: If you are installing Sage for the first time, read the document "About Sage" carefully.
# The document is in ~/Library/TeXShop/Engines/Inactive/Sage.

PATH=$PATH:/Library/TeX/texbin:/usr/texbin:/usr/local/bin
filename=$1
sagename=${filename/%tex/sagetex.sage}
soutname=${filename/%tex/sagetex.sout}
# above line replaces original; thanks to Carl Crisman

pdflatex --file-line-error --synctex=1 "$filename"

# do we need to run Sage?
if [ -f "$soutname" ]
then
#	new_sum=$(egrep -v '^( _st_.goboom|print .SageT)' "$sagename" | egrep -v '(_st_.current_tex_line)' | md5)
new_sum=$(egrep -v '^( _st_.goboom|print .SageT)|(_st_.current_tex_line|SageTeX pause|SageTeX unpause)' "$sagename" | md5)
#   above line replaces original line below; thanks to Markus Baldauf
#   new_sum=$(egrep -v '^( _st_.goboom|print .SageT)' "$sagename" | md5)
   old_sum=$(egrep -o ^%[0-9a-f]{32}% "$soutname" | cut -b 2-33)
   if [ "$new_sum" != "$old_sum" ]
   then
       run_sage=yes
   fi
else
   # no .sout file, so run Sage
   run_sage=yes
fi

if [ "$run_sage" = "yes" ]
then
   echo Running Sage, please wait a moment...
   /usr/local/bin/sage "$sagename"
   pdflatex --file-line-error --synctex=1 "$filename"
else
   echo No Sage commands have changed, so running Sage is unnecessary.
fi
