#!/usr/bin/perl

#
# Speciell diff för PO-filer.
# $Id: extrDiffs,v 1.5 1997/04/14 19:44:21 jhd Exp $
#
require 5.000;
use Getopt::Long;

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

$Getopt::Long::bundling = 1;
&GetOptions("g|gammal=s", "n|ny=s") || &usage;

sub usage
{
  die "Usage: $0 [--gammal=prefix] [--ny=prefix] old-file new-file\n" .
      "  -g,  --gammal:  Prefix före gamla meddelanden (standardvärde \"G \")\n" .
      "  -n,  --ny:  Prefix före nya meddelanden (standardvärde \"N \").\n";
}

$opt_g = "G " unless $opt_g;
$opt_n = "N " unless $opt_n;
$pad = length($opt_g);
$pad = length($opt_n) if length($opt_n) > $pad;
$pad = " " x $pad;

&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 -u0 -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 "$pad$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 "$pad$x";
    }

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

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

