eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}' # -*-perl-*-
    & eval 'exec perl -S $0 $argv:q'
    if 0;
#----
use strict;
use File::Path;
use Getopt::Std;

my %options=();
my $outdir="squelette";

getopts("o:h",\%options);

if ($options{h}) {
    print "Usage: generer-squelette.pl -o DESTDIR FILES\n";
    print "Takes a list of files, like foo/bar.txt and foo/boz.txt\n";
    print "and generates squeleton-ified versions, like\n";
    print "DESTDIR/foo/bar.txt and DESTDIR/foo/boz.txt\n";
    exit 0;
}

$outdir = $options{o} if defined $options{o};
$outdir =~ s@/*$@@;
mkpath [$outdir];

my $total_supprime = 0;
my $total_files = 0;

our $source;
our $lineno;

foreach (@ARGV) {
    # Accessed from error()
    local $source = $_;
    local $lineno = 0;
    my $dest = "$outdir/$_";
    my $cut = 0;
    my $supprime = 0;
    
    sub error {
        print ": ERROR\n";
        my $abspath = File::Spec->rel2abs($source);
        print "$abspath:$lineno: $_[0]\n";
        exit 1;
    }

    print "$source -> $dest";
    open(INPUT, $source);
    my $destdir = $dest;
    $destdir =~ s@/[^/]*$@@;
    mkpath [$destdir];
    open(OUTPUT, '>', $dest) or die("Unable to open $dest");

    while(<INPUT>) {
        $lineno++;
        if (/START CUT( |\*\/)*$/) {
            if ($cut == 0) {
                $cut = 1;
            } else {
                error("Two START CUT in serie");
            }
        } elsif (/END CUT( |\*\/)*$/) {
            if ($cut == 1) {
                $cut = 0;
            } else {
                error("Two END CUT in serie, or no START CUT");
            }
        } elsif (/TO DELETE( |\*\/)*$/) {
            $supprime++;
        } elsif (! $cut) {
            s/-- *UNCOMMENT *//;
            s/\/\* *UNCOMMENT *(.*?) *\*\//$1/;
            s/\/\/ *UNCOMMENT *//;
	    s/# *UNCOMMENT *//;
	    s/ *\/\* *CUT END-OF-LINE *\*\/.*//;
            print OUTPUT $_;
        } else {
            $supprime++;
        }
    }

    if ($cut == 1) {
        error("START CUT not closed by END CUT.\n");
    } elsif ($supprime > 0) {
        print ": \033[3;31m$supprime lines removed.\033[0m\n";
        $total_supprime += $supprime;
        $total_files++;
    } else {
        print ".\n";
    }

    my $inmode = (stat INPUT)[2] & 0111; # executable bit only
    my $outmode = (stat OUTPUT)[2];
    close(INPUT);
    close(OUTPUT);
    chmod $inmode | $outmode, $dest
}

print "Total: $total_supprime lines removed in $total_files file(s).\n";
