#! /usr/bin/perl -CSD
use strict;

my ($Prog, $Version) = ("weave0", "2.0.3");
my $Lib_dir = ".";
my (@Code_opt, @Lang_opt, @Pre_opt);
my @Pre_files = ();
my $F_prog = "";
my $L_prog = "";
my $Verbose = 0;
$_ = "latex";   &Usage unless $_;
my $pr = "$Lib_dir/w0-f-$_";
if (-r $pr) { 
    $F_prog = $pr;
} else {
    &Message("Filter $_ is unknown;", "use of -f option ignored.");
};
PARAM:
while (@ARGV) { $_ = shift;
    /^-e$/ and do { push @Lang_opt, "-e";  next PARAM; };
/^-f$/ and do { $_ = shift;
    &Usage unless $_;
my $pr = "$Lib_dir/w0-f-$_";
if (-r $pr) { 
    $F_prog = $pr;
} else {
    &Message("Filter $_ is unknown;", "use of -f option ignored.");
};  next PARAM; };
/^-f(.+)/ and do { $_ = $1;
    &Usage unless $_;
my $pr = "$Lib_dir/w0-f-$_";
if (-r $pr) { 
    $F_prog = $pr;
} else {
    &Message("Filter $_ is unknown;", "use of -f option ignored.");
};  next PARAM; };
/^-l$/ and do { $_ = shift;  
    &Usage unless $_;
my $pr = "$Lib_dir/w0-l-$_";
if (-r $pr) { 
    $L_prog = $pr;
} else {
    &Message("Language $_ is unknown;", "use of -l option ignored.");
};  next PARAM; };
/^-l(.+)/ and do { $_ = $1;
    &Usage unless $_;
my $pr = "$Lib_dir/w0-l-$_";
if (-r $pr) { 
    $L_prog = $pr;
} else {
    &Message("Language $_ is unknown;", "use of -l option ignored.");
};  next PARAM; };
/^-o$/ and do { $_ = shift or &Usage;
    push @Code_opt, "-o'$_'";  next PARAM; };
/^-o(.+)/ and do {
    push @Code_opt, "-o'$1'";  next PARAM; };
/^-v$/ and do {
    print STDERR "This is $Prog (version $Version)\n";
    push @Pre_opt, "-v";  push @Lang_opt, "-v";  
    push @Code_opt, "-v";  $Verbose = "Yes";  next PARAM; };
/^-/ and do {
    &Message("Unknown option `$_' ignored.");  next PARAM; };

    push @Pre_files, "'$_'";
}
my $Pre_cmd = "$Lib_dir/w0pre @Pre_opt @Pre_files";
my $Post_cmd = "";
$Post_cmd .= "$L_prog @Lang_opt | " 
    if $L_prog;
$Post_cmd .= "$F_prog @Code_opt";

&Message("Running $Pre_cmd | $Post_cmd") if $Verbose;
open(PRE, "$Pre_cmd |");
open(POST, "| $Post_cmd");
print POST while <PRE>;
close PRE;  exit $?>>8 if $?>>8;
close POST;  exit $?>>8;

sub Usage {
    print STDERR "Usage: $Prog [-e] [-f filter] [-l language]",
                 " [-o file] [-v] [file...]\n";
    exit 1;
}
sub Error {
    &Message(@_);  
    &Tidy_up if defined &Tidy_up;
    exit 1;
}
sub Message {
    print STDERR "$Prog: ", shift, "\n";
    while (@_) {
        print STDERR " "x(2+length $Prog), shift, "\n";
    }
}
