#!/usr/bin/perl -w

use Common;
use strict;

my %inc;
my %gnuplot;
my $dvips;
my %cmd;
my $pgsize; # a4 and a5 are supported

sub Usage() {
  print "Usage:
	depend_tex tex-file(s)
";
  exit 1;
}

sub tex_inc( $ ) {
  my $file = shift;
  my $fh;
  my %lst = ();
  my $main_file = 0;

  open($fh, "<", $file) || return 0;
  while(<$fh>) {
    s/%.*$//; # get rid of comments
    tr/ \t\r\n/ /s;
    s/^ //;
    s/ $//;
    last if (m/^\\end\{document\}/); # fails when it is part of a macro

    if (m/\\documentclass/) { $main_file = 1; } # TODO: better test for top tex file
    if (m/\\documentclass\[ ?(.*) ?\]/ || m/\\usepackage\[ ?(.*) ?\]\{(crop|geometry)\}/) {
	my @fld = grep { m/^a\d(paper)?$/ } split(/ ?, ?/, $1);
	#print "$_//$file \@fld: ", join(" ", @fld), "\n";
	if (@fld) {
	    $fld[0] =~ m/^(a\d)/;
	    $pgsize = $1;
	    #print "$file: $pgsize\n";
	}
	next;
    }

    if (m/\\usepackage.*\{biblatex\}/) {
	$cmd{biblatex}++;
	next;
    }

    # this breaks when the files are included from a macro, and
    # if the command is on more than one line
    # TODO: INL and m/#\d/: INL is the hardcoded macro name, better detection of a macro would be needed
    m/\\(INL|bibliography|include|input|includegraphics)(\[[^\]]+\])?\{([^\}]+)\}/ || next;
    next if ($3 =~ m/#\d/);
    my $cmd = $1;
    my $inc_file = $3;
    $cmd{$cmd}++;
    my $stem;
    # add possible extension
    if ($inc_file =~ m/(.+)\.(.){1,5}$/) {
	$stem = $1;
      # if it has a 1-5 letter extension, we don't need to add any
    } else {
	$stem = $inc_file;
	if ($cmd eq "biblatex" || $cmd eq "bibliography") {
	    $inc_file .= ".bib";
	} elsif ($cmd eq "include") {
	    $inc_file .= ".tex";
	} elsif ($cmd eq "input") {
	    $inc_file .= ".tex";
	} elsif ($cmd eq "includegraphics") {
	    $inc_file .= ".eps"; # depends on latex version
	} else {
	}
    }

    if ($cmd eq "includegraphics" && $inc_file =~ m/(.*)-\d+.eps$/) {
	# dependancy wise, we are simply using just one of the file included from:
	#my $stem = $1;
	if (-f "$stem.ly") {
#	    $inc_file = $stem . ".tex";
	    #print STDERR "TST: $stem $inc_file\n";
	}
    }

#    if ($cmd eq "input" && $inc_file =~ m/(.*)-systems.tex$/) {
#      $dvips .= " -h $1.psfonts";
#    }
    if ($cmd eq "input" && -f "$stem.plot") {
	$gnuplot{$stem}++;
    }

    # mark files to be recursively checked for dependencies
    if ($cmd eq "input" && $inc_file =~ m/\.tex$/ && !$inc{$inc_file}) {
      if ($inc_file =~ m/-systems.tex$/) {
	  # handled by Makefile rule
      } else {
	$lst{$inc_file} = 1;
      }
    }

    # we must condider non-existant files, they can be generated
    $inc{$inc_file} = 1;
  }
  close($fh);

  foreach (keys(%lst)) {
    &tex_inc($_);
  }
  return $main_file;
}

#if (@ARGV < 1) { Usage(); }
if (@ARGV < 1) { exit 0; }

my $all = "";
my $file;
foreach $file (@ARGV) {
  # reset found dependancies for each new file to check
  %inc = ();
  %cmd = ();
  $pgsize = "";
  $dvips = "";
  if (&tex_inc($file)) {
    my $stem = $file;
    $stem =~ s/\.(la)?tex$//;
    my $lst = join(" ", sort(keys(%inc)));
    #if ($pgsize) { $dvips .= " -t $pgsize"; } # dvips doesn't need this if "pagesize" special is in the dvi file
    $all .= " $stem.ps";

    # .dvi target
    print "$stem.dvi:\t$file ", $lst, "\n";
    print "\tlatex \$*\n";
    if ($cmd{"biblatex"}) {
      print "\tlatex \$*\n";
      print "\tbiber \$*\n";
    } elsif ($cmd{"bibliography"}) {
      print "\tbibtex \$*\n";
    }
    print "\tlatex \$*\n";

    # .ps target
    print "$stem.ps:\t$stem.dvi\n";
    print "\tdvips $dvips $stem\n";
    print "\tps2pdf14 $stem.ps  $stem.pdf\n";
    # remake the postcript file to make it level 2 instead 3
    # (so I can print on my old printer)
    print "\tpdftops  $stem.pdf $stem.ps2\n";

    # .bk.ps target
    print "$stem.bk.ps:\t$stem.ps\n";
    if ($pgsize eq "a4") {
	print <<EOT;
	~/psutils-1.17/psbook -r  $stem.ps2 > $stem.tmp1.ps
	psnup -2 -s 1 -pa3 $stem.tmp1.ps | fixtd > $stem.bk.ps
	ps2pdf -sPAPERSIZE=a3 $stem.bk.ps
	pstops -pa3 '2:0L(297mm,0mm)+1L(297mm,210mm)'  $stem.ps2 $stem.lf.ps
EOT
    } elsif ($pgsize eq "a5") {
	if ($stem =~ m/libretto/) {
	    print <<EOT;
# this is special to make a text booklet fitting into a dvd box
	pstops '2:0(-15.25mm,0),1(15.25mm,0)' $stem.ps2 > $stem.tmp1.ps  # adjust for margins
	~/psutils-1.17/psbook -r $stem.tmp1.ps > $stem.tmp2.ps  # make pages in right order
	psnup -s1 -2 -pa4 $stem.tmp2.ps > $stem.tmp3.ps  # two on a page
	pstops '2:0,1U(210mm,298mm)' $stem.tmp3.ps | fixtd > $stem.bk.ps  # duplex on long side => odd pages upside-down
EOT
	} else {
	    print <<EOT;
	~/psutils-1.17/psbook -r  $stem.ps2 > $stem.tmp1.ps
	psnup -2 -s 1 -pa4 -Pa5 $stem.tmp1.ps | fixtd -tumble > $stem.bk.ps
	ps2pdf -sPAPERSIZE=a4 $stem.bk.ps
	pstops -pa4 '2:0L(210mm,0mm)+1L(210mm,148.5mm)'  $stem.ps2 $stem.lf.ps
EOT
	}
	print "\tps2pdf -sPAPERSIZE=a4 $stem.bk.ps\n";
    } elsif ($pgsize eq "a3") {
	# ignore it for the moment
    } else {
	print STDERR "unhandled pagesize: <$pgsize> in <$file>\n";
    }
    print <<EOT;
	psselect _1-_1     $stem.bk.ps $stem.bk.a.ps
	psselect _2-_2     $stem.bk.ps $stem.bk.b.ps
	psselect -p-_3     $stem.bk.ps $stem.bk.c.ps
EOT

    print "\n";
  }
}
for my $k (keys %gnuplot) {
    print "$k.tex:	$k.plot\n";
    #print "\tgnuplot \$<\n";
}
print "\n";
print "all:\t$all\n\n";
