#!/usr/bin/perl

$oldfile=$ARGV[0];
$newfile=$ARGV[1];

$outfile=$newfile.".CB";

open(NEWFILE, "$newfile") || die "$newfile: $!\n";
open(OUTFILE, ">$outfile")|| die "$outfile: $!\n";

# probably is GNU diff dependant.
open(DIFF, "diff --unified=0 -B -i -w $oldfile $newfile|") || die "diff: $!\n";

$diffline=0;
$newline=0;

#
# diff output looks like:
#
#@@ -62,10 +62,10 @@
#-   1.    Introduction . . . . . . . . . . . . . . . . . . . . . . . .  4
#-   1.1   But what about authentication? . . . . . . . . . . . . . . .  5
#-   2.    Terminology and Reference diagrams . . . . . . . . . . . . .  6
#-   2.1   Reference diagram  . . . . . . . . . . . . . . . . . . . . .  6
#-   2.1.1 Terminology  . . . . . . . . . . . . . . . . . . . . . . . .  6
#-   3.    Project Goals and Requirements . . . . . . . . . . . . . . .  8
#-   4.    Brief overview of method used  . . . . . . . . . . . . . . .  9
#-   5.    Detailed description of process  . . . . . . . . . . . . . . 12
#-   5.1   IPsec packet interception  . . . . . . . . . . . . . . . . . 12
#-   5.2   DNS lookup for rTXT record . . . . . . . . . . . . . . . . . 12
#+   1.    Introduction . . . . . . . . . . . . . . . . . . . . . . . .  5
#+   1.1   But what about authentication? . . . . . . . . . . . . . . .  6
#+   2.    Terminology and Reference diagrams . . . . . . . . . . . . .  7
#+   2.1   Reference diagram  . . . . . . . . . . . . . . . . . . . . .  7
#+   2.2   Terminology  . . . . . . . . . . . . . . . . . . . . . . . .  7
#+   3.    Project Goals and Requirements . . . . . . . . . . . . . . .  9
#...
#
# Only the @@ ... @@ lines are important, and only the second piece, as
# this tells us which lines in the new file have actually changed.
#
# We try to nuke one space from the line from some convenient place, e.g.
# where there are two consecutive spaces. This keeps things aligned if
# possible.
#

while(<DIFF>) {
  $diffline++;
  next unless(/@@ (.*) (.*) @@/);

  $old = $1;
  $new = $2;
    
#  if($old =~ m/(.*)\,(.*)/) {
#    $oldspot = $1;
#    $oldcnt  = $2;
#  } else {
#    $oldspot = $old;
#    $oldcnt = 1;
#  }
  
  if($new =~ m/(.*)\,(.*)/) {
    $newspot = $1-1;
    $newcnt  = $2;
  } else {
    $newspot = $new-1;
    $newcnt = 1;
  }
    
  # now, copy NEWFILE to OUTFILE until we get to $newspot.
  while($newline < $newspot) {
    $_ = <NEWFILE>;
    $newline++;
    print OUTFILE $_;
  }
    
  # now, copy $newcnt lines from NEWFILE to OUTFILE, putting |.
  while($newcnt > 0) {
    $_ = <NEWFILE>;
    $newline++;

    # refrain from marking blank lines
    if(m,^\s*$,) {
      # blank line
      print OUTFILE $_;
    } else {
      # nuke one space if possible
      s/  / /;
      print OUTFILE "|".$_;
    }
    $newcnt--;
  }
}
