#/usr/local/bin/perl

if($#ARGV<0 or $ARGV[0] =~ /^-h/) {
    print "Syntax:\n";
    print "\n\tsnr.pl [options] <file> <perl-style-regexp-filter>\n";
    print "\nPurpose:";
    print "\n\tfilters <file> according to perl style regexp <filter>.";
    print "\n\tprints on stdout unless -m is specified.  The flag -m";
    print "\n\t denotes to mutate the file instead.  Regexp can";
    print "\n\thave spaces.\n\n";
    print "Example:\n";
    print "\tsnr.pl -m MyClass.java s/byte /int /g\n\n";
    exit;
}

#defaults:
$mutate=0;
$oneline=0;

#options:
$c=0;
while($c <= $#ARGV+1 and $ARGV[$c] =~ /^\-/) {
	$arg=$';
	if($arg eq "m" or
	   $arg eq "mutate") {
	    $mutate=1;
	} elsif($arg =~ /^l/) {
	    $oneline=1;
	} else {
	    die "SNR: unknown option -$arg in argument number $c.";
	}
	$c++;
}

#parameters:
$needed=2;

$found = $#ARGV+1-$c;
if($found < $needed) {
    die "SNR: found $found parameters.  Need exactly $needed.\n";
}

$fname=$ARGV[$c];

@tmp=@ARGV;
for($d=0;$d<$c+1;$d++) {
	shift @tmp;
}
$myregexp=join(" ",@tmp);

#substitute piping symbols
$myregexp =~ s/\&lt\;/\</g;
$myregexp =~ s/\&gt\;/\>/g;
$myregexp =~ s/\&pipe\;/\|/g;

#get file
open(F,$fname) or die "SNR: file \"$fname\" not found\n";

#get temp file
if($mutate) {
	$tempfn=join("",$fname,".tmp");
	open(TEMP,join("","> ",$tempfn)) or 
		die "SNR: cannot write temp file $tempfn";
}

if($oneline) {
	undef $/;                      # read whole file
}

while($line=<F>) {
	eval("\$line =~ $myregexp;");
	if($mutate) {
		print TEMP $line;
	} else {
		print STDOUT $line;
	}
}

if($mutate) {
	close(TEMP) or die "SNR: could not close temp file";
	close(F) or die "SNR: could not close input file";
	rename($tempfn,$fname) or 
	    die "could not rename $tempfn to $fname";
} else {
	close(F) or die "SNR: could not close input file";
}
