#!/usr/bin/perl -n

sub usage {
    warn("usage: xgettext-ocaml --output <pot file> [--keyword WORD ]* <files...>\n");
    exit(1);
}

BEGIN { 
    use Getopt::Long;

    my @keywords = ('i18n', 'i18n_');
    GetOptions('output=s' => \$output_file,
	       'keyword=s' => \@keywords,
	      ) or usage();
    $output_file && @ARGV or usage();

    $keywords = '(?:' . join('|', map { quotemeta } @keywords) . ')';
}

sub add_it {
    my (@l) = @_;

    my $msg = join('', map { qq("$_"\n) } @l);
    push @msgs, $msg;
    push @{$msg2pos{$msg}}, "$ARGV:$.";
}

if (@multi_line) {
    if (/(([^\\"]*|\\.)*)"/) {
	add_it('', @multi_line, $1);
	@multi_line = ();
    } else {
	chomp;
	push @multi_line, $_ . '\n';
    }
} elsif (/\b$keywords\s*"(([^\\"]*|\\.)*)"/) {
    add_it($1);
} elsif (/\b$keywords\s*"(([^\\"]*|\\.)*)\n/) {
    push @multi_line, $1 . '\n';
}

close ARGV if eof; # to reset $.

END {
    open STDOUT, "> $output_file" or die "can't write output file $output_file: $!\n";

    my $date = `date '+%Y-%m-%d %H:%M%z'`;
    chomp $date;
    printf(<<'HEADER', $date);
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: %s\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"
HEADER

    foreach my $msg (@msgs) {
	my $poss = delete $msg2pos{$msg} or next;

	print "\n";
	print "#: ", join(' ', sort @$poss), "\n";
	print "#, c-format\n";
	print qq(msgid $msg);
	print qq(msgstr ""\n);
    }
}
