#!/usr/bin/perl
use warnings;
use strict;

my %dict;

sub ensure_entry {
    my ($string) = @_;

    $dict{$string} = []
        unless exists $dict{$string};
}


while (<>) {
    chomp;
    my $file = $_;
    open SOURCE, "<:encoding(UTF-8)", $file
        or die "Error opening '$file' for reading: $!";

    my $line_no = 0;
    my $cont = 0;
    my $line = '';
    while (my $l = <SOURCE>) {
        ++$line_no;
        chomp($l);
        # Handle continuation lines
        if ( $l =~ m/\s*_$/) {
            $line .= $l;
            --$line_no; ++$cont;
            next;
        } else {
            $line .= $l;
        }
        if ( $cont ) {
            $line =~ s/'\s*_\s*'//g;
        }
        if (my @matches = $line =~ m/(?<!make)text\s*\(\s*"((?:\\.|[^"])*)"/g) {
            foreach my $match (@matches) {
                if ($match !~ m/(?<!\\)\$/g) {
                    &ensure_entry($match);
                    push @{$dict{$match}}, "#: $file:$line_no";
                }
                else {
                    warn "$file:$line_no: Direct variable interpolation not supported; use bracketed ([_1]) syntax! ($match)";
                }
            }
        }
        elsif (@matches = $line =~ m/(?<!make)text\s*\(\s*'((?:''|[^'])*)'/g) {
            foreach my $match (@matches) {
                # recode 'match' to double quoting
                $match =~ s/''/'/g;
                $match =~ s/\\/\\\\/g;
                $match =~ s/"/\\"/g;

                &ensure_entry($match);
                push @{$dict{$match}}, "#: $file:$line_no";
            }
        }
        $line = ''; $line_no += $cont; $cont = 0;
    }
    close SOURCE;
}

foreach my $string (sort keys %dict) {
    foreach my $location (@{$dict{$string}}) {
        print "$location\n";
    }
    print "msgid \"$string\"\n";
    print "msgstr \"\"\n\n";
}
