#!/usr/bin/perl -w
use Data::Dumper;

open (FD, "english.lng") or die;
while($s=<FD>){
    chomp($s);
    die if ($s!~/^([0-9A-Z_]+),.*?(".*")/);
    $english{$1}=$2;
    push @keys,$1;
}
close(FD);


fix("czech", \%english);

if (@ARGV>0){
    print "exiting...\n";
    exit(0);
}
    
open (FD, "czech.lng") or die;
while($s=<FD>){
    chomp($s);
    die if ($s!~/^([0-9A-Z_]+),.*?(".*")/);
    $czech{$1}=$2;
}
close(FD);

fix("slovak", \%czech);
fix("german", \%english);
fix("portuguese", \%english);
fix("french", \%english);
fix("castellano", \%english);
fix("polish", \%english);
fix("italian", \%english);

parsesources();

sub fix {
    my ($name, $parent)=@_;
    my ($key, $value);
    my (%lng);

    print "Fixing $name\n";
    open (FD, "$name.lng") or die;
    while($s=<FD>){
        chomp($s);
        die if ($s!~/^([0-9A-Z_]+),.*?(".*")/);
        $lng{$1}=$2;
    }
    close(FD);

    open (FD, ">$name.lng") or die;
    foreach $key (@keys){
        if (defined($lng{$key})){
            $value=$lng{$key};
        }else{
            print "undefined key '$key'\n" if (!defined($$parent{$key}));
            $value=$$parent{$key};
        }
        print FD "$key, $value,\n";
    }
    close(FD);
}


sub parsesources{
    my ($f, $file, $s, $reg, $key, $unused,$contents);
    my (%used);
    
    opendir(DD, "../src") or die;

    foreach $f (readdir(DD)){
        $file="../src/$f";
        next if (! -f $file);
        next if ($file!~/\.c$/ && $file!~/\.h$/);
        next if ($file=~/language\.h$/);
        next if ($file=~/\/del_/);

#        print Dumper($file);

        open(FD, $file) or die;
        $contents="";
        while ($s=<FD>){
            $contents.=$s;
        }
        foreach $key (@keys){
            $reg="$key";
            if ($contents=~/$reg/m){
                $used{$key}=1;
            }
        }
        close(FD);
    }
    closedir(DD);

    $unused="";
    foreach $key (@keys){
        next if ($key=~/^T__/);
        next if (defined($used{$key}));
        if (length($unused)>0) {
            $unused.=", ";
        }
        $unused.=$key;
    }
    if (length($unused)>0) {
        print "Unused keys: $unused\n";
    }
}


