#!/usr/local/bin/perl -w

=head SYNOPSIS

	strings_2_po.pl stringsFile poFile > newPoFile

	takes the strings file, merges with the po file, replacing any strings from
	the latter with ones from the former, creating a new po file.

=head AUTHOR

	Raphael Finkel <raphael@cs.uky.edu>
	9/2003
	GPL

=cut

($#ARGV == 1) || die ("Usage: $0 stringsFile poFile.\nStopping");

open(STRINGS, $ARGV[0]) || die ("Can't open $ARGV[0].  Stopping");
while (defined ($line = <STRINGS>)) { # one line of strings
	$line =~ /^([A-Za-z_]+)="([^"]*)"/ or next;
	$name = $1;
	$value = $2;
	$contents{$name} = $value;
	$contents{$name} =~ s/&#x000a;/\\n"\n"/g;
	$contents{$name} =~ s/&#10;/\\n"\n"/g;
	$contents{$name} =~ s/&#9;/\\t/g;
	$contents{$name} =~ s/&amp;/\&/g;
	$contents{$name} =~ s/&lt;/</g;
	$contents{$name} =~ s/&gt;/>/g;
	$contents{$name} =~ s/&quot;/\\"/g;
	# print "** I know that $1 => $2\n";
} # one line of strings
close STRINGS;

open(PO, $ARGV[1]) || die ("Can't open $ARGV[0].  Stopping");
while (defined ($line = <PO>)) { # one line of po
	chomp $line;
	if ($line =~ /^#\. ([A-Za-z_]+)$/) { 
		$name = $1;
		if (defined($msgstr) and $msgstr ne $contents{$name}) {
			# print STDERR "*** $name introduces new string: $msgstr\n";
			$postponed{$name} = $contents{$name};
			next;
		}
		$msgstr = $contents{$name};
		# print "** noting $1 => [$msgstr]\n";
		print $line, "\n";
	} elsif ($line =~ /^msgstr "/ and defined($msgstr)) {
		# print "** replacing with [$msgstr]\n";
		print "msgstr \"$msgstr\"\n";
		$msgstr = undef;
		do {$line = <PO>; last unless defined($line);} until $line !~ /^"/;
			# skip continuation lines
		last unless defined($line);
		redo;
	} elsif ($line eq "") {
		# print "** forgetting\n";
		print "\n";
		$msgstr = undef;
	} elsif ($line =~ /^msgid "(.*)"\s*$/) {
		# print "remembering msgid $1 ...\n";
		$msgid = $1;
		print $line, "\n";
		while (1) { # record continuation lines
			$line = <PO>;
			last unless defined($line);
			last unless $line =~ /^"(.*)"$/;
			# print "continuation: $line\n";
			print $line;
			$msgid .= $1;
		}
		foreach $name (keys %postponed) {
			next if defined($msgid{$name});
			# print "$name has msgid \"$msgid\"\n";
			$msgid{$name} = $msgid;
		}
		last unless defined($line);
		redo;
	} else {
		# print "** copying\n";
		print $line, "\n";
	}
} # one line of po
close PO;

foreach $name (keys %postponed) {
	print "\n#. $name\n" ,
		"#: inconsistent msgstr in strings file\n" ,
		"msgid \"$msgid{$name}\"\n" ,
		"msgstr \"$postponed{$name}\"\n";
}

