#!/bin/zsh
zmodload zsh/zselect

REMOTE_VIM_ID=GVIM-$RANDOM
export REMOTE_VIM_ID

cd $(dirname "$1")
1=$(basename "$1" .tex)

gvim --servername $REMOTE_VIM_ID "$1.tex"

while [ ! -e "$1.tex" ]; do
  # 4/10 of a second
  zselect -t 40
done

pdflatex --synctex=1 "$1"
touch "$1.pdf"

scriptpid=$$

(
  # awful awful hack
  sleep 4
  evince_vim_dbus.py GVIM $REMOTE_VIM_ID "$1.pdf" "$1.tex"
) &
dbusthingpid=$!

echo evince_vim_dbus.py pid is $dbusthingpid

(
  evince "$1.pdf"
  kill $scriptpid
  kill $dbusthingpid
  exit
) &

# Only if you have the modified  whaw
# puts windows that are selected side by side
if which whaw >/dev/null 2>&1 ; then
  if whaw --help | grep htile >/dev/null ; then
    whaw -d --htile
  fi
fi


while :; do
  if [ "$1.pdf" -ot "$1.tex" ]; then
    if pdflatex --synctex=1 --interaction nonstopmode "$1" ; then
      echo evince reloadeths itself
    else
      echo
      echo 'ERROR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
      if [ -z "$QUIET" ]; then
        echo -en '\a'
	ogg123 /usr/share/sounds/gnome/default/alerts/bark.ogg
      fi
      echo
      touch "$1.pdf"
    fi
  fi
  # 4/10 of a second
  zselect -t 40
done
