#! /usr/local/bin/perl

$nocase = 0;
$reverse = 0;
while($ARGV[0] =~ /^-/) {
	if ($ARGV[0] eq '-i') {
		$nocase = 1;
		shift;
		next;
	}
	if ($ARGV[0] eq '-v') {
		$reverse = 1;
		shift;
		next;
	}
	print STDERR "$0: unknown option $ARGV[0]!\n";
	exit(1);
}

$pattern = shift;
##$pattern =~ s/([^a-zA-Z0-9])/\\\1/g;
$show_files = ($ARGV[1] ne '') ? 1 : 0;

sub check {
		$hit = 0;
		if ($nocase) {
			$hit = 1 if (/$pattern/i);
		} else {
			$hit = 1 if (/$pattern/);
		}
		if ($reverse) {
			$hit = ($hit) ? 0 : 1;
		}
		if ($hit) {
			print "$ARGV: " if $show_files;
			print $_
		}
}

if ($ARGV[0]) {
	while ($ARGV = shift) {
		open(ARGV, $ARGV);
		while (<ARGV>) {
			&check;
		}
		close(ARGV);
	}
} else {
	while (<STDIN>) {
		&check;
	}
}
exit(0);
