

sub readlexicon {
    my $fn=shift;
    open(IN,$fn);
    my %lexicon=();
    my $contents=join('',<IN>);
    close(IN);
    $contents=~s/package Apache\:[^\;]+//;
    $contents=~s/use base[^\;]+//;
    eval($contents.'; %lexicon=%Lexicon;');
    delete $lexicon{'_AUTO'};
    delete $lexicon{'char_encoding'};
    delete $lexicon{'language_code'};
    return %lexicon;
}

sub readnew {
    open(IN,'newphrases.txt');
    my %lexicon='';
    while (my $line=<IN>) {
	chomp($line);
	$lexicon{$line}=$line;
    }
    close(IN);
    return %lexicon;
}

# ==== Main Program

my %master=&readnew();

foreach (<*.pm>) {
    print "Reading: ".$_."\n";
    %master=(%master,&readlexicon($_));
}

# Remove obsolete from synch

open(IN,'removephrases.txt');
while (my $line=<IN>) {
    chomp($line);
    delete $master{$line};
}
close(IN);


foreach my $fn (<*.pm>) {
    print "Synching: ".$fn."\n";
    my %lang=&readlexicon($fn);
    system ("cp $fn $fn.original");
    open(IN,$fn.'.original');
    open(OUT,'>'.$fn);
    my $found=0;
    while (<IN>) {
	if ($_=~/\#\s*SYNCMARKER/) { $found=1; last; } 
	print OUT $_;
    }
    if ($found) {
	print OUT "\n\#SYNC ".localtime()."\n";
	foreach my $key (sort keys %master) {
	    unless ($key) { next; }
	    unless ($lang{$key}) {
		my $comment='';
		my $copytrans=$key;
		foreach (reverse sort keys %lang) {
		    $copytrans=~s/$_/$lang{$_}/gsi;
		}
		if (lc($copytrans) ne lc($key)) {
		    $comment='# '.$copytrans;
                }
		print OUT (<<ENDNEW);
   '$key'
=> '$key',
$comment
ENDNEW
	    }
	}

	print OUT "\n\#SYNCMARKER\n";
	foreach (<IN>) {
	    print OUT $_;
	}
    }
    close (IN);
    close (OUT);
}
