#!/usr/bin/perl

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 ($line =~ m/(?<!make)text\s*\(\s*"((\\.|[^"])*)"/) {
            my $match = $1;

            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 ($line =~ m/(?<!make)text\s*\(\s*'((''|[^'])*)'/) {
            my $match = $1;

            # 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 (keys %dict) {
    foreach my $location (@{$dict{$string}}) {
        print "$location\n";
    }
    print "msgid \"$string\"\n";
    print "msgstr \"\"\n\n";
}
