#!/usr/bin/perl -w
#
# $Revision: 1.4 $ $Date: 2012-07-26 17:11:47-04 $
# $Source: /home/vogelke/bin/RCS/cgrep,v $
# $Host: sys7.com $
# $UUID: c5898149-5206-3a6f-9c58-be444aea84ee $
#
#<cgrep: context grep: look for lines around a pattern
# Usage: cgrep [-lines] pattern [files]

use strict;

my $context = 3;
my @ary;
my ($seq, $old);

# They might want more or less context.

if ($ARGV[0] =~ /^-(\d+)$/) {
    $context = $1;
    shift;
}

# Get the pattern and protect the delimiter.

my $pat = shift;
$pat =~ s#/#\\/#g;

# First line of input will be middle of array.
# In the eval below, it will be $ary[$context].

$_ = <>;
push(@ary, "   $.\t$_");

# Add blank lines before, more input after first line.

for (1 .. $context) {
    unshift(@ary, '');
    $_ = <>;
    push(@ary, "   $.\t$_") if $_;
}

# Now use @ary as a silo, shifting and pushing.

while ($ary[$context]) {
    if ($ary[$context] =~ /$pat/) {
        $old = $ary[$context];
        $ary[$context] =~ s/^  />>/;
        print "------\n" if $seq++;
        print @ary;
        $ary[$context] = $old;
    }
    $_ = <> if $_;
    shift(@ary);
    push(@ary, "   $.\t$_") if $_;
}

exit(0);
