#!/usr/bin/perl

#$Id: xmpost,v 1.1 1999/05/10 17:14:27 pedros Exp $

open OFILE, ">$ARGV[0]" or die " can't open $ARGV[0].pl:$!\n";
open IFILE, "<$ARGV[0].mp" or die " can't open $ARGV[0].mp:$!\n";
open XCMDFILE, ">$ENV{\"HOME\"}/.xcmd/$ARGV[0]" or die " can't open ~/.xcmd/$ARGV[0]:$!\n";

my $tmp_mp_file = "$ARGV[0].$$";

my $i=$j=0;

while(<IFILE>){
#  s/\s*(\w+)\s*\t*\s*:*=\s*([\(0-9,-.\)]*);/\t$1\t:=\$opt_$1;/;
  $lines[$j++]=$_;
  if($_ =~ /\s*(\w+)\s*\t*\s*:=\s*([\(0-9,-.\)]*);/){
    print XCMDFILE "OPTION_WITH_ARG --$1 DEFAULT \"$2\"\n";
#    print OFILE "\t$1\t\t:=\$opt_$1;\n";
    $arr[$i++]="\$opt_$1";
  }
}
close IFILE;

print OFILE "#!/usr/bin/perl\n\n";
print OFILE " use vars qw(";

foreach $i (0..$#arr-1){
  print OFILE "$arr[$i] ";
}
print OFILE "$arr[$#arr]);\n\n";

print OFILE "\n\nuse Getopt::Long;\n\n";


foreach $i (0..$#arr){
  print OFILE "$arr[$i]=\"\";\n";
}
print OFILE "\n\nGetOptions(";
foreach $i (0..$#arr-1){
  $arr[$i] =~ s/\$opt_//;
  print OFILE "\"$arr[$i]=s\",";
}
$arr[$#arr] =~ s/\$opt_//;

print OFILE "\"$arr[$#arr]=s\") || die \"Aborted\";\n";
print OFILE "\$file = \"$tmp_mp_file\";\n";
print OFILE "\nopen TMP, \">/tmp/\$file.mp\" || die \"can't open /tmp/\$file.mp \$!\\n\";\n";

foreach $j (0..$#lines){
  $_ = $lines[$j];
  chop;
  s/\%/\\\%/g;
  s/\\/\\\\/g;
  s/\$/\\\$/g;
  s/\s*(\w+)\s*\t*\s*:=\s*([\(0-9,-.\)]*);/\t$1\t\t:= \$opt_$1;/;
  print OFILE "print TMP \"$_\\n\";\n";
}
print OFILE "close TMP;\n";

print OFILE "\$tmp = `inimpost featpost.mp`;\n";
print OFILE "\$tmp = `mpost -mem featpost /tmp/\$file.mp`;\n";
print OFILE "\$tmp = `laproof /tmp/\$file 1`;\n";

my $tmp = `chmod +x $ARGV[0]`;
$tmp = `cp $ARGV[0].mp /tmp/$tmp_mp_file.mp`;
$tmp=  `inimpost featpost.mp`;
$tmp = `mpost -mem featpost /tmp/$tmp_mp_file.mp`;
$tmp = `laproof /tmp/$tmp_mp_file 1`;
system("gv -watch $tmp_mp_file.1.eps &");
system("xcmd $ARGV[0] &");
