#!/usr/local/bin/perl

$output = "";

while ($#ARGV >= 0) {
    $_ = $ARGV[0];
    last unless (/^-/);
    $output  = $ARGV[1], shift, shift, next    if (/^-o$/);
    printf STDERR ("Unknown option '%s', ignored\n", $_);
    shift;
}

if ($output) {
    if ($output eq "-") {
	open(OUT, ">&STDOUT");
    } else {
	open(OUT, ">$output") || die("Cannot create $output: $!");
    }
}

foreach $infile (@ARGV) {
    open(IN, $infile) || die("Cannot open $infile: $!");
    if (! $output) {
	$outfile = $infile;
	$outfile =~ s/\.tex$//;
	open(OUT, "> $outfile.f.tex")
	    || die("Cannot create $outfile.f.tex: $!");
    }
    while(<IN>) {
	if (m/^\\begin{caml_code}\s*$/) {
	    print OUT "\\caml\n";
	    while(<IN>) {
		last if m/\\end{caml_code}\s*$/;
		s/\\/\\\\/g;
		print OUT "\\?", $_;
		print OUT "\\;" if m/;;\s*$/;
	    }
	    print OUT "\\endcaml\n";
	}
	elsif (m/^\\begin{caml_hidden}\s*$/) {
	    while(<IN>) {
		last if m/^\\end{caml_hidden}\s*$/;
	    }
	}
	else {
	    print OUT $_;
	}
    }
    close(IN);
}
