#! perl -w
# If you want to modify grep to do something specific see SimpleGrep.
# This version of grep is written for speed not clarity.
use RISCOS::Throwback 'throwback_info';
use RISCOS::Filespec;
use RISCOS::File 'globlist';
use Getopt::Std;

use vars qw($opt_c $opt_i $opt_t $opt_v $count);

delete $SIG{'__DIE__'};
delete $SIG{'__WARN__'};

if (defined $ARGV[0] and $ARGV[0] eq '-throwback') {
    $throw = 1;
    $pattern = shift;
} else {
    $throw = 0;
}
getopts ('icvt');

$pattern = shift @ARGV;

die "$0 [-throwback] [-c] [-v] [-i] pattern [files]" unless $pattern;

@ARGV = globlist( @ARGV );

$count = 0;
$throw = 1 if $opt_t;

$lots = @ARGV > 1;

if ($lots)
{
    # Onlyprint the filename if more than one
    $printit = "print \"\$ARGV: \$_\";";
    $printc =  "print \"\$ARGV: \$count\n\"";
} else {
    $printit = 'print;';
    $printc =  "print \"\$count\n\"";
}


$prog = '
while( <> )
{
    next ' . ($opt_v ? 'if' : 'unless') . '/$pattern/o' . ($opt_i ? 'i' : '') .
    ';' . ($opt_c ? '$count++;' : $printit) .
  
($throw ? 'chomp; throwback_info( $ARGV, $., $_ );' : '') . '
} continue {
  if (eof) {
' . ($opt_c ? "if (\$count) {$printc; \$count = 0; }" : '') . '
    close(ARGV); # Reset line numbers for each file
  }
}
1';

eval $prog or die $@;	# Run the beastie
