#!perl -w
# NAME: cleandiff.pl
# AIM: To remove some things from an input diff file ...
# 1 - remove Only in blah blah ...
# 2 - remove diff of .dsp files ...
# and write results to an output file
# 11/2/2008 geoff mclane http://geoffair.net/fg
use strict;
use warnings;

my $in_file = 'tempdiff.txt';
my $out_file = 'temp2diff.txt';

parse_args(@ARGV);

process_file($in_file, $out_file);

exit(0);

sub give_help {
	prt( "Brief HELP for $0 script ...\n" );
	prt( "$0 -in:input_file -out:output_file\n" );
	ort( "Defaults: in:$in_file, out:$out_file\n" );
	exit(0);
}

sub parse_args {
	my (@av) = @_;
	my ($arg, $ch, $val);
	while(@av) {
		$arg = shift @av;
		$ch = substr($arg,0,1);
		if ($arg =~ /\?/) {
			give_help();
		} elsif (($ch eq '-')||($ch eq '/')) {
			$val = substr($arg,1);
			if ($val =~ /^in:/) {
				$in_file = substr($val,3);
				prt( "Set input file to $in_file ...\n" );
			} elsif ($val =~ /^out:/) {
				$out_file = substr($val,4);
				prt( "Set output file to $out_file ...\n" );
			} else {
				prt( "ERROR: Unknown argument [$arg]!\n" );
				give_help();
			}
		} else {
			prt( "ERROR: Unknown argument [$arg]!\n" );
			give_help();
		}
	}
}

sub prt {
	my ($txt) = shift;
	print $txt;
}

sub process_file {
	my ($fil, $out) = @_;
	my (@lines, $line, $lncnt, $i, $txt, $lnnum);
	my @nlines = ();
	my $newlns = 0;
	if (open INF, "<$fil") {
		@lines = <INF>;
		close INF;
		$lncnt = scalar @lines;
		prt( "Process $lncnt lines from $fil ...\n" );
		$lnnum = 0;
		for ($i = 0; $i < $lncnt; $i++) {
			$line = $lines[$i];
			chomp $line;
			$lnnum++;
			if ($line =~ /^Only\s+in\s+/) {
				next;
			} elsif ($line =~ /^diff\s+.+\.dsp$/i) {
				$i++;
				for (; $i < $lncnt; $i++) {
					$line = $lines[$i];
					chomp $line;
					if ($line =~ /^diff\s+.+/) {
						if ( !($line =~ /^diff\s+.+\.dsp$/i) ) {
							last;
						}
					}
				}
			}
			push(@nlines,$line);
			$newlns++;
		}
		$txt = join("\n",@nlines);
		if (open OUT, ">$out") {
			print OUT $txt;
			close OUT;
			prt("Written $newlns to $out ... discarded ".($lncnt - $newlns)." lines ...\n" );
		} else {
			prt( "ERROR: Unable to CREATE/WRITE file $out ... check name, location...\n" );

		}
	} else {
		prt( "ERROR: Unable to OPEN/READ file $fil ... check name, location...\n" );
	}
}

# eof - cleandiff.pl
