#!/usr/bin/perl

use strict;
use vars qw( %Translate %seen $TranslationFile );
%Translate = ();

sub ReadFile {
  my ($fileName) = @_;
  my ($data);
  local $/ = undef;   # Read complete files

  if (open(IN, "<$fileName")) {
    $data=<IN>;
    close IN;
    return (1, $data);
  }
  return (0, "");
}

sub ReadFileOrDie {
  my ($fileName) = @_;
  my ($status, $data);

  ($status, $data) = &ReadFile($fileName);
  if (!$status) {
    die("Can not open $fileName: $!");
  }
  return $data;
}

die "Usage: $0 translationfile >> updatedfile"  unless scalar(@ARGV) <= 1;
$TranslationFile = $ARGV[0];
require $TranslationFile  if $TranslationFile;
%seen = ();

@ARGV = glob("*.pl");

sub PrintHeader {
  my $trans = &ReadFileOrDie($TranslationFile);
  my ($head) = $trans =~ /^(.*)%Translate/s;
  print $head;
}

sub trans {
  my ($string) = @_;
  my ($result);

  $result = '';
  $result = $Translate{$string}  if (defined($Translate{$string}));

  return ' '  if ($seen{$string});
  $seen{$string} = 1;
  print $string . "\n" . $result . "\n";
  return ' ';
}

&PrintHeader()  if $TranslationFile;
print '%Translate = split(\'\n\',<<\'END_OF_TRANSLATION\');' . "\n";
foreach (<>) {
  s/T\(\'([^']+)/&trans($1)/ge;
  s/Tss?\(\'([^']+)/&trans($1)/ge;
  s/T\(\"([^"]+)/&trans($1)/ge;
  s/Tss?\(\"([^"]+)/&trans($1)/ge;
}

print "END_OF_TRANSLATION\n";
