#!/usr/bin/perl -w

use strict;
use utf8;

my (%strings);
my ($base,$tmpl,$out);

sub read_strings {
	my $filename = shift;
	my $fh;
	my $ctx = -1;
	my ($lang,$id,$str);
	open($fh,'<:utf8',$filename) or die "Cannot open strings.";
	foreach (<$fh>) {
		if ($ctx < 0) {
			if (/^BEGIN/) {
				$ctx = 0;
				$id = '';
			}
			next;
		}
		s/^\s+//;s/\s+$//;
		if ($ctx == 0) {
			if (/^\w+$/) {
				$id = $_;
				$ctx = 1;
			}
		} else {
			if (/^\s*$/) {
				$ctx = 0;
				$id = '';
			}
			if (/^\w+:/) {
				($lang,$str) = /^(\w+): ?(.*)$/;
				if (not exists $strings{$lang}) {
					$strings{$lang} = {};
				}
				$strings{$lang}->{$id} = $str;
			}
		}
	}
	close($fh);
}

sub sub_tmpl {
	my ($lang,$lang_id,$sublang_id,$lang_name) = @_;
	my $lang_strings;
	my ($type,$id);
	if (defined $strings{$lang}) {
		$lang_strings = $strings{$lang};
	} else {
		$lang_strings = {};
	}
	seek($tmpl,0,0);
	foreach (<$tmpl>) {
		($type,$id) = /\{(.)(\w+)\}/;
		while ($id) {
			my $rep = '';
			if ($type eq '#') {
				if ($id eq 'language') {
					$rep = $lang_name;
				} elsif ($id eq 'lang') {
					$rep = $lang_id;
				} elsif ($id eq 'sublang') {
					$rep = $sublang_id;
				}
			} elsif ($type eq '$') {
				if (defined $lang_strings->{$id}) {
					$rep = '"' . $lang_strings->{$id} . '"';
				} else {
					$rep = '""';
				}
			}
			s/\{.\w+\}/$rep/;
			($type,$id) = /\{(.)(\w+)\}/;
		}
		print $out $_;
	}
}

read_strings($ARGV[0]);

open($base,"<:utf8",$ARGV[1]) or die "Cannot open base.";
open($tmpl,"<:utf8",$ARGV[2]) or die "Cannot open template.";
open($out,">:utf8",$ARGV[3]) or die "Cannot open output.";

foreach (<$base>) {
	if (/^{.\w+=.*}/) {
		my ($type,$lang,$args) = /^\{(.)(\w+)=(.*)\}/;
		my @args = split /\s*,\s*/, $args;
		if ($type eq '@') {
			sub_tmpl($lang, @args);
		}
		next;
	}
	print $out $_;
}

close($base);
close($tmpl);
close($out);
