#
# make sketch documentation with Windows and Cygwin
#
use strict;
use File::Copy;

our $GS = "gswin32.exe";
our $MEM_OPTION = "--extra-mem-top=5000000"; # MikTeX 2.7
# our $MEM_OPTION = ""; # MikTeX 2.6

sub make_example {
  my $ex = shift;
  die "missing example name" unless $ex;
  my %arg = map { $_ => 1 } @_;
  
  unless ($arg{nosketch}) {
    my $cmd = "sketch -D $ex manexamples.sk > $ex.tex";
    print STDERR "$cmd\n";
    system($cmd) == 0 or die;
  }
  unless ($arg{nobitmaps}) {
    print STDERR "latex example '$ex-tmp.tex':\n";
    system("sed -e s/TEXFILE/$ex/ makeex-tmp.tex > $ex-tmp.tex") == 0 or die;
    system("latex $MEM_OPTION $ex-tmp.tex") == 0 or die;
    system("dvips -E $ex-tmp -o $ex.eps") == 0 or die;
    local *F;
    open(F, "> $ex.txt") or die;
    print F "Image $ex omitted in text version of this document.";
    close F;
    system("$GS -q -dQUIET -dNOPAUSE -dBATCH -dEPSCrop -sDEVICE=pdfwrite -sOutputFile=$ex.pdf -r120 $ex.eps") == 0 or die;
    system("$GS -q -dQUIET -dNOPAUSE -dBATCH -dEPSCrop -sDEVICE=png256   -sOutputFile=$ex.png -r120 $ex.eps") == 0 or die;
    unlink <$ex-tmp.*>;
  }
}

sub make_all {
  my %arg = map { $_ => 1 } @_;
  if ($arg{examples}) {
    local *F;
    open(F, "tags.sk") or die;
    while (<F>) {
      if (/<([^>]*)>/) {
        make_example $1, @_;
      }
    }
    close(F);
  }
  unless ($arg{notypeset}) {
    print "info:\n";
    system("makeinfo sketch.texi") == 0 or die;

    print "html, one page per node:\n";
    system("makeinfo --html sketch.texi") == 0 or die;
    while (<*.png>) { 
      copy($_, "sketch/$_");
    }

    print "html, single page:\n";
    system("makeinfo --html --no-split sketch.texi") == 0 or die;

    # run twice to ensure labels are ok
    print "TeX DVI\n";
    system("texi2dvi sketch.texi") == 0 or die;
    system("texi2dvi sketch.texi") == 0 or die;

    print "Postscript:\n";
    system("dvips sketch.dvi -o sketch.ps") == 0 or die;

    # texi2dvi finds PNG before the PDF graphics, so delete...
    my @unlink_list = <ex???.png>;
    unlink @unlink_list;

    # make PDF manual
    print "PDF:\n";
    system("texi2dvi --pdf sketch.texi") == 0 or die;

    # ... and restore
    for (@unlink_list) {
      copy("sketch/$_", $_);
    }
  }
}

if (grep { /help/ } @ARGV) {
  print "usage: perl make.pl [examples] [nosketch] [nobitmaps] [notypeset]\n";
}
elsif ($ARGV[0] =~ /^ex[0-9]+/ ) {
  make_example @ARGV
}
else {
  make_all @ARGV
}
