#!/usr/bin/perl

use strict;
use warnings;

# Read i18n.c and scan

my @i18nstart;
my @i18nend;
my %Strings;

open FILE,"< i18n.c" or die "open";
while (<FILE>) {
	push @i18nstart,$_;
	last if ($_ =~ /i18nscan start/);
}

if (eof(FILE)) {
	die "i18nscan start not found";
}

while (<FILE>) {
	last if ($_ =~ /i18nscan end/);
	push @i18nstart,$_;
	
	if ($_ =~ /\{ "([^"]*)"/) {
		$Strings{$1}=0;
	}
}
push @i18nend,$_;

if (eof(FILE)) {
	die "i18nscan end not found";
}

while (<FILE>) {
	push @i18nend,$_;
}
close FILE;


# Read all files

opendir DIR,"." or die "opendir";
my @files=grep { /.c$/ || /.h$/ } readdir DIR;
closedir DIR;

for my $file (@files) {
	open FILE,"< $file" or die "open $file";
	while (<FILE>) {
		my $line=$_;
		for my $tr ($line =~ /tr\("([^"]*)"\)/g) {
			if (defined $Strings{$tr}) {
				if ($Strings{$tr}==0) { $Strings{$tr}=1; }
			} else {
				print "New: $tr\n";	
				$Strings{$tr}=2;
			}
		}		
	}
	close FILE;	
}


# Write new file

rename "i18n.c","i18n.c~";

open FILE,"> i18n.c" or die "open";
for my $text (@i18nstart) {
	print FILE "$text";
}

for my $str (sort keys %Strings) {
	if ($Strings{$str}==2) {
		print FILE "  { \"$str\",\n";
		for (1..18) {
			print FILE "    \"\", // TODO\n";
		}
		print FILE "    \"\"  // TODO\n";
		print FILE "  },\n";
	} elsif ($Strings{$str}==0) {
		print "Old: $str\n";	
	}
}

for my $text (@i18nend) {
	print FILE "$text";
}
