#! /usr/bin/perl

# http://l10n.openoffice.org/extract_merge.html

sub reading {
    my $hashref = shift;
    my $langref = shift;
    my ($key, $value);
    while (<ARGV>) {
	next if m/\A\#/;
	next if m/\A\s*\Z/;
	#Project SourceFile Dummy ResourceType GroupId LocalId HelpId Platform Width LanguageId ...
	($Project,
	 $SourceFile,
	 $Dummy,
	 $ResourceType,
	 $GroupId,
	 $LocalId,
	 $HelpId,
	 $Platform,
	 $Width, 
	 $LanguageId)
	    = split(m/\t/, $_);
	unless ($LanguageId) {
	    printf STDERR "Warning: No LanguageId is specified: %s %n: %s", $ARGV, $., $_;
	    next;
	}
	if ($LanguageId eq "en-US") {
	    printf STDERR "Warning: en-US is included: %s %n: %s", $ARGV, $., $_;
	    next;
	}
	$key = join("\t", $Project, $SourceFile, $Dummy, $ResourceType, $GroupId, $LocalId);
	$value = $LanguageId;
	$$hashref{$key}{$value} ++;
	$$langref{$value} ++;
    } continue {
	# reset line numbering on each input file
	close ARGV  if eof;     # Not eof()!
    }
}

sub mycmp {
    my @a = split(m/\t/, $a);
    my @b = split(m/\t/, $b);
    my $ret;
    foreach my $x (@a) {
	$y = shift @b;
	if ($x =~ m/\A[0-9]/) {
	    $ret = $x <=> $y;
	}
	else {
	    $ret = $x cmp $y;
	}
	return $ret unless $ret == 0;
    }
    return 0;
}

sub main {
    my %data;
    my %lang;
    reading(\%data, \%lang);

    # header
    my @lang = sort keys %lang;
    print join("\t", qw( Project SourceFile Dummy ResourceType GroupId LocalId ));
    foreach my $lang (@lang) {
	print "\t$lang";
    }
    print "\n";

    # body
    my $value;
    foreach my $key (sort { mycmp } keys %data) {
	print "$key";
	foreach my $lang (@lang) {
	    $value = $data{$key}{$lang} + 0;
	    print "\t$value";
	}
	print "\n";
    }
}

main();

__END__

    
