#! /usr/bin/perl -w

use utf8;
use strict;
use open qw/:std :encoding(utf8)/;
use Encode;

# call with pairs of strings, first the wrong string, second the replacement
# strings must be escaped like in the po-file

my %rep;
while(@ARGV)
{
  my $from = Encode::decode("utf-8", shift @ARGV);
  my $to = Encode::decode("utf-8", shift @ARGV);
  $rep{$from} = $to;
  print "'$from' -> '$to'\n";
}

for my $po (reverse sort glob("po/*.po"))
{
  local $/;
  $/ = "\n\n";
  open my $in,'<:encoding(utf-8)',$po or die;
  my $outpo = $po;
  $outpo =~ s/.*\///;
  open my $out,'>',$outpo or die;
  my $changed = 0;

  for my $line (<$in>)
  {
    $line =~ s/"\n"//g;
    print $out $line if $line =~ /msgid ""\nmsgstr/;
    for my $f (keys %rep)
    {
      if($line =~ s/msgid "\Q$f\E"\nmsgstr/msgid "$rep{$f}"\nmsgstr/ && $line !~ /msgstr ""/ && $line !~ /msgstr "$f"/)
      {
        print $out $line;
        ++$changed;
      }
    }
  }
  close($out);
  unlink($outpo) if !$changed;
}
