#!/bin/csh -fb
#
# grep for comment lines containing the search string.
#
# USAGE:
#   grcomment search_string file_list
#
rm -f /tmp/gr_$argv[1]_matches /tmp/gr_$argv[1]_out
egrep -ni $argv > /tmp/gr_$argv[1]_matches
set wcmatch = (`wc /tmp/gr_$argv[1]_matches`)
set nmatch = $wcmatch[1]
@ count = 0
#
# check if only a single file in grep list
#
@ lastarg = $#argv
if ($lastarg == "2" ) then
  set singfl = "true"
else
  set singfl = "false"
endif
#
# for each match search for continuation lines and print to 
# standard output.
#
while ($count < $nmatch)
  @ count ++
  if ($singfl == "true") then
    set file = (`cut -d: -f 1 /tmp/gr_$argv[1]_matches`)
    set lfile = $argv[$lastarg]
    set line = (`cut -d: -f 1 /tmp/gr_$argv[1]_matches`)
  else
    set file = (`cut -d: -f 1 /tmp/gr_$argv[1]_matches`)
    set lfile = $file[$count]
    set line = (`cut -d: -f 2 /tmp/gr_$argv[1]_matches`)
  endif
#
# define start and end lines of match.
#
  @ start = $line[$count]
  @ endln = $line[$count] 
  set before = "false"
  set after = "true"
#
# check to see if current line is a continuation line.
#
  @ prevln = $start - 1
  sed -e "$prevln,$prevln w /tmp/gr_$argv[1]_out" $lfile > /dev/null
  set comm = `cut -c 1 /tmp/gr_$argv[1]_out`
  sed -e "$start,$start w /tmp/gr_$argv[1]_out" $lfile > /dev/null
  set cont = `cut -c 6 /tmp/gr_$argv[1]_out`
  if ( $comm == "c" || $comm == "C" || $cont != "" ) then
    set before = "true"
  endif
#
# check for lines before and after.
#
  while ($before == "true")
    if ($start == 1) then
      set before = "false"
    endif
    @ start --
    sed -e "$start,$start w /tmp/gr_$argv[1]_out" $lfile > /dev/null
    set comm = `cut -c 1 /tmp/gr_$argv[1]_out`
    if ( $comm != "c" || $comm != "C" ) then
      set before = "false"
    endif
  end
  while ($after == "true")
    @ endln ++
    sed -e "$endln,$endln w /tmp/gr_$argv[1]_out" $lfile > /dev/null
    set comm = `cut -c 1 /tmp/gr_$argv[1]_out`
    if ( $comm == "" ) then
      set after = "false"
      @ endln --
    endif
  end
  sed -e "$start,$endln w /tmp/gr_$argv[1]_out" $lfile > /dev/null
  if ($start == $endln) then
    echo $lfile':'$start':'
  else
    echo $lfile':'$start'-'$endln':'
  endif
  cat /tmp/gr_$argv[1]_out
  echo
#
# check if next match has been printed.
#
  if ( $count < $nmatch ) then
    set ok = "false"
  else
    set ok = "true"
  endif
  while ($ok == "false")
    @ next = $count + 1
    if ( $next >= $nmatch ) then
      set ok = "true"
    else if ( $file[$next] != $file[$count] ) then
      set ok = "true"
    else if ( $line[$next] <= $endln) then
      @ count ++
    else if ( $line[$next] > $endln) then
      set ok = "true"
    endif
  end
end
# rm -f /tmp/gr_$argv[1]_matches /tmp/gr_$argv[1]_out
