#!/usr/bin/perl

#
# Speciell diff för PO-filer.
#
require 5.000;

$0 =~ s:.*/::;

sub usage
{
    die "Usage: $0 old-file new-file\n";
}

&usage unless @ARGV == 2;

die "$0: Can't read $ARGV[0]: $!\n" unless -r $ARGV[0];
die "$0: Can't read $ARGV[1]: $!\n" unless -r $ARGV[1];

open(DIFFOUT, "diff -U 0 -wBb -I '^#' $ARGV[0] $ARGV[1] |");

sub findClosest
{
    my($in, $lineno) = @_;
    while ($lineno > 0) {
      last if $in->[$lineno] =~ /^\s*$/;
      last if $lineno == 1;
      $lineno--;
    }
    $lineno;
}

open(IN, $ARGV[1]);
@in = <IN>;
unshift(@in, "");

OUTER:
while (<DIFFOUT>) {
  next if /^---/ || /^\+\+\+/;  # Skip headers.

  while (/@@\s+-\d+(,\d+)?\s+\+(\d+)(,\d+)?\s+@@/) {
    my $lineno = $2;
    my @hunk;
    my $valid;

    $_ = <DIFFOUT>;
    while ($_ && ! /^@@/) {
      push(@hunk, $_);
      $valid = 1 if /^\+[^#]/;
      $_ = <DIFFOUT>;
    }

    #print "\@\@ $lineno\n", @hunk;
    next if ! $valid;

    if ($l > 2) {
      until ($l == $lineno || $in[$l] =~ /^msgid / || $l > @in) {
	print " $in[$l]";
	last if $in[$l++] =~ /^\s*$/;
      }
    }

    $close = &findClosest(\@in, $lineno);
    $close = $l if $close < $l;
    for ($l = $close; $l < $lineno; $l++) {
      $x = $in[$l];
      print " $x";
    }

    foreach $line (@hunk) {
      $l++ unless $line =~ /^-/;
      next if $line =~ /^-#/;
      print $line;
    }
  }
}

until ($in[$l] =~ /^\s*$/ || $in[$l] =~ /^msgid / || $l > @in) {
  print " $in[$l++]";
}
