#!/usr/bin/perl

($logd, $texd, $targd, $mkd) = @ENV{'logd', 'texd', 'targd', 'mkd'};
$scrfile = "$mkd/build1.sh";
open SCF, ">$scrfile" || die "cannot write to $scrfile";
print SCF <<BEG;
#!/bin/sh

BEG

sub build_tex {
  my ($nam, $opt, $flgs, $cont) = @_;
  my $tnam = "$texd/$nam.tex";
  print stdlog "creating $tnam\n";
  open TF, ">$tnam" || die "cannot create $tnam";
  print TF <<ST;
\\documentclass[$opt,leqno]{article}
\\usepackage[francais]{babel}
\\usepackage{a4wide}
\\usepackage{isolatin1}
\\usepackage{amsmath}
\\usepackage{amssymb}
\\usepackage{mathrsfs}
\\usepackage[all]{xy}
\\hoffset=-6mm

\\input macros
ST
  for my $fv (split (/\,/, $flgs)) {
    if ($fv =~ /^([a-z]+)\=([a-z]+)$/) { print TF "\\$1$2\n"; }}
  print TF "\n\\begin{document}\n\n";
  for my $c (split (//, $cont)) {
    $c = "0$c" if ($c =~ /^[AB]$/);
    print TF '\input RS', $c eq 't' ? '_toc' : $c, "\n"; }
  print TF "\n\\end{document}\n";
  close TF;
}

@arg = ();

while (<>) {
  if (/^\{([A-Za-z\-\_0-9\.]+)\}\{(.+)\}\{(.*)\}\{(.*)\}\{(.*)\}\s*$/) {
    @arg0 = @arg;
    ($name, $descr, @arg) = ($1, $2, $3, $4, $5);
    print <<TERM;
<dt>$1: <a href=$1.dvi>dvi</a>
  <a href=$1.ps>ps</a>
  <a href=$1.dvi.gz>dvi.gz</a>
  <a href=$1.ps.gz>ps.gz</a>
  <a href=$1.dvi.bz2>dvi.bz2</a>
  <a href=$1.ps.bz2>ps.bz2</a>
  <dd>$2
</dt>
TERM
    for my $i (0 .. 2) { $arg[$i] = $arg0[$i] if ($arg[$i] eq '-'); }
    print SCF "\$mkd/makeit $1\n";
    if ($5 ne '') { &build_tex ($name, @arg); }
  } else { print $_; }
}

close SCF;
