#! /bin/sh

DELAY=1
# 0: on demand (press enter to get it compiling)
# else, delay in seconds betwen recompilations


##
## End of configuration. No need to edit below (normally)
##

# Parse the arguments
usage () {
  echo usage: $0 [--nolaunch] target
  exit 1
}

need_launch=yes
while [ x$# != x0 ] ; do
  case $1 in
    --nolaunch) need_launch=no ;;
    --no)       need_launch=no ;;
    --nl)       need_launch=no ;;
    -*)
      usage
      ;;
    *)
      if [ "x$TARGET" != x ] ; then
        usage
      fi
      TARGET=$1
      ;; 
  esac
  shift
done

if [ "x$TARGET" = "x" ] ; then
  TARGET_COUNT=`ls *pdf|grep -v cpy.pdf|wc -l`
  if [ "x$TARGET_COUNT" = "x1" ] ; then
    TARGET=`ls *pdf|grep -v cpy.pdf`
    echo "Et jamais tu précise que la cible est $TARGET ??"
  else
    echo "Cannot choose between `ls *pdf|grep -v cpy.pdf`"
    usage
  fi
fi

if echo $TARGET | grep -q 'tex$' ; then
  TARGET=`basename $TARGET .tex`.pdf
  echo Cretin tu voulais dire tex_watch $TARGET
fi
if echo $TARGET | grep -q '\.$' ; then
  TARGET="$TARGET"'pdf'
  echo Cretin tu voulais dire tex_watch $TARGET
fi

##
## Relance le xpdf au besoin
##

if [ "x$need_launch" = "xyes" ] ; then
  make $TARGET || exit 1 
  cp $TARGET cpy.pdf; 
  xpdf -z page -remote watch -quit ;
  xpdf -z page -remote watch cpy.pdf & 
  echo "XX Launch"
else 
  echo "XX Refresh"
  cp $TARGET cpy.pdf; 
  xpdf -remote watch -reload
fi

##
## Entre en boucle infinie
##

while true ; do 
  if [ "x$DELAY" != "x0" ] ; then
    sleep $DELAY ;
  else 
    read dummy
  fi
  make $TARGET
  if [ "x$?" != "x0" -o $TARGET -ot cpy.pdf ] ; then 
    :
  else 
    cp $TARGET cpy.pdf
    echo "XX Reload"
    xpdf -remote watch -reload
  fi
done
