#!/usr/bin/perl

@TODO=(); # list of files to translate

sub translate_word
{
    my $input = $_[0];
    my $output;
    if (exists($dead_keys_dict{$input}))
    { $output = $dead_keys_dict{$input}; }
    else
    { $output = $input; }
    return $output;
}

sub translate_file
{
    my $infile=$_[0]; my $outfile=$_[1];
    open(INPUT, $infile) or die "Couldn't open $infile.\n";
    open(OUTPUT, ">$outfile") or die "Couldn't open $outfile.\n";

    print "Processing $infile.\n";
    print OUTPUT "#This file is autogenerated from $infile.\n#Do not edit.\n\n";

    my $file;
    while (<INPUT>)
    {
        if (/^\#PXC.*<(.*?)>.*?=>.*?<(.*?)>/) # if this is a virtual to pseudo keysym indication
        {
            $dead_keys_dict{$1} = $2;
        }
        if (/^include.*.pxc\"/)  # if this is an include line of a .pxc
        {
            s/\"(.*).pxc\"/\"$1.xcompose\"/;  # updating file name in the line
            my $file=$1;                      # fetching file name
            $file =~ s/%H/$ENV{HOME}/e;       # %H is XCompose for $HOME
            push(@TODO, "$file.pxc");         # file must be treated.
        }
        s/<(.*?)>/"<".translate_word($1).">"/eg;  # translating line
        print OUTPUT unless (/^\#PXC/);           # outputing line (except directives)
    }
    close(OUTPUT); close(INPUT);
    return;
}

sub translate_all
{
    my $infile, $outfile;
    foreach $infile (@TODO)
    {
        $outfile = $infile;
        $outfile =~ s/.pxc/.xcompose/;
        translate_file($infile, $outfile);
    }
}

push(@TODO,$ARGV[0]);
translate_all();
