#!/usr/bin/perl
#
# Author : mth
# Created: 2003-06-02
#
# $RCSfile$
# $Author: egonw $
# $Date: 2003-07-25 12:39:24 +0200 (Fri, 25 Jul 2003) $
# $Revision: 1197 $
#
# cd to the Jmol directory and run me in order to resolve
# cvs conflicts in the headers of .java files after a merge
#
# IMPORTANT: it resolved any conflict, whether in the header
# or not. Use 'grep -R -n "<<<<<"' to see in which lines the
# conflicts are found. The '-n' option outputs the line number,
# which is 2 for conflicts in the header. Resolve conflicts
# with other line numbers PRIOR to running this script!
#
# The "conflict" files generated by CVS are saved as .java.bak
#
# This will probably only work on a Linux/Unix system
#
use strict;

my $endheaderlinenumber = 15; # set arbitrarily

open(CONFLICT, 'find src -name \*.java | xargs grep -l "<<<<<" |');
while (<CONFLICT>) {
    chop;
    fixConflict($_);
}

sub fixConflict {
    my $filename = $_;
    print "Fixing header conflict in $filename\n";
    my $filenameBak = $filename . ".bak";
    rename $filename, $filenameBak;
    open(IN, "<$filenameBak");
    open(OUT, ">$filename");
    my $state = 'lookingForConflict';
    my $linenumber = 0;
    while (<IN>) {
	my $line = $_;
    $linenumber++;
	if ($state eq 'lookingForConflict') {
	    if ($line =~ /^<<<<</) {
            if ($linenumber < $endheaderlinenumber) {
                $state = 'discardingBeforeDoubleBar';
                next;
            } else {
                print "Skipping conflict starting at line $linenumber!\n";
            }
	    }
	    if ($line =~ /\s*(final|public|private|abstract|class)/) {
		$state = 'copyingFile';
	    }
	    print OUT $line;
	    next;
	}
	if ($state eq 'discardingBeforeDoubleBar') {
	    if ($line =~ /^=====/) {
		$state = 'copyingAfterDoubleBar';
	    }
	    next;
	}
	if ($state eq 'copyingAfterDoubleBar') {
	    if ($line =~ /^>>>>>/) {
		$state = 'lookingForConflict';
	    } else {
		print OUT $line;
	    }
	    next;
	}
	print OUT $line;
    }
    close IN;
    close OUT;
}
