#!/usr/bin/perl -w

use strict;

use Getopt::Long;
use constant DEBUG => 0;

my $opt_config;
my $opt_help;
my $opt_outdir;
my $opt_icon;

my @optl;
push(@optl, "c=s" => \$opt_config);
push(@optl, "h" => \$opt_help);
push(@optl, "o=s" => \$opt_outdir);
push(@optl, "i=s" => \$opt_icon);
Getopt::Long::Configure("bundling_override");
if (!GetOptions(@optl) or $opt_help or !$opt_config ) {
    my $progname = $0;
    $progname =~ s,.*/(.*),$1,;
    print "Usage:  $progname -c \"CONFIG VALUES\" [-o outputdir] [-i iconSize] [files]\n";
    exit 2;
}

my @config = split(/\s+/, $opt_config);
my %replace;

while(my $file = shift) {
    unless ( open(INFILE, "<$file") ) {
	warn "Could not open file $file\n";
	next;
    }
    my $text = "";
    my %skip;

    while ( defined($_ = <INFILE>) ) {
	my $found;
	my @tag;

	@tag = ();
	$found = 0;
	while ( s/%%([^%]+)%%// ) {
	    $found = 1;
	    push( @tag, $1 );
	}
	if ( $found ) {
	    my $word = join(" ", @tag);
	    DEBUG and print "start tag $word\n";
	    if ( !exists($skip{$word}) ) {
		$skip{$word} = 1;
	    } else {
		warn "$file: $word already in use\n";
	    }
	    next if ( /^\s*$/ );
	}

	@tag = ();
	$found = 0;
	while ( s/@@([^@]+)@@// ) {
	    $found = 1;
	    push( @tag, $1 );
	}
	if ( $found ) {
	    my $word = join(" ", @tag);
	    DEBUG and print "end tag $word\n";
	    if ( exists($skip{$word}) ) {
		delete $skip{$word};
	    } else {
		warn "$file: $word not in use\n";
	    }
	    next if ( /^\s*$/ );
	}

	my $print = 0;
	for my $word ( keys %skip ) {
	    my $found = 0;
	    for my $tag ( split(/\s+/, $word) ) {
		DEBUG and print "checking '$tag'\n";
		if ( grep(/^$tag$/, @config) ) {
		    $found = 1;
		    last;
		}
	    }
	    if ( $found ) {
		$print++;
	    }
	}   

	next if ( $print != scalar(keys %skip) );

	if ( /^\{(\w+)\}=\{([^}]+)\}$/ ) {
	    $replace{$1} = $2;
	    next;
	}

	# special case that the next one can't handle
	if ( /^\$\$\{(\w+)\}/ ) {
	    my $replacement = defined($replace{$1})?$replace{$1}:"";
	    s/^\$\$\{(\w+)\}/$replacement/;
	}
	while ( /([^\\])\$\$\{(\w+)\}/ ) {
	    my $replacement = $1.defined($replace{$2})?defined($replace{$2}):"";
	    s/([^\\])\$\$\{(\w+)\}/$replacement/;
	}
	s/\\(\$\$\{\w+\})/$1/g;

	$text .= $_;

    }

    close INFILE;
    if ($opt_outdir && $text !~ /^\s*$/) {
	open(OUTFILE, ">$opt_outdir/$file");
	print OUTFILE $text;
	close OUTFILE;
    } else {
	print $text;
    }
}

exit 0;

