#! /usr/bin/perl

$defaultLatexCmd = "platex";
$defaultXdviCmd = "xdvi-ja";

if (@ARGV < 1) {
  print STDERR "Usage: xdvi-poll.pl FILE [LATEXCMD] [XDVICMD]\n";
  exit(1);
}

$texfile = $ARGV[0];
$latexbin = $ARGV[1];
$xdvibin = $ARGV[2];

if ($texfile =~ /(.*)\.[^.]*$/) {
  $texfiletrunk = $1;
}

unless (defined($latexbin)) {
  $latexbin = $defaultLatexCmd;
}

unless (defined($xdvibin)) {
  $xdvibin = $defaultXdviCmd;
}

system("$latexbin $texfile < /dev/null") && die "cannot compile $texfile";

if (!defined($pid = fork())) {
  die "cannot fork: $!";
} elsif ($pid == 0) {
  exec("$xdvibin $texfiletrunk.dvi");
}

$prevlastmodified = 0;
while (10) {
  $lastmodified = -M $texfile;
  if ($lastmodified != $prevlastmodified) {
    system("$latexbin $texfile < /dev/null");
    $procs = `/bin/ps -ea | /bin/grep $xdvibin | /bin/sed -e 's/^ *//' -e 's/ .*//'`;
    $procs =~ s/\n/ /g;
    system("kill -USR1 $procs");
  }
  $prevlastmodified = $lastmodified;
  sleep(1);
}
