#! /usr/bin/gawk -f

BEGIN { 
  USAGE = (ARGV[0] " -vPAT=XXX [ -vCTX=NNN | -vLCTX=NNN -vRCTX=NNN ]")

  # Enumerates all occurrences of PAT in the input file,
  # with LCTX chars of context on the left and RCTX on the right.
  # (The CTX option applies to both left and right.)
  # Lines are implicitly padded with CTX underscores on either side.

  if (PAT == "") { print "usage: " USAGE > "/dev/stderr"; exit 1; }
  if (CTX != "") 
    { 
      if((LCTX != "") || (RCTX != ""))
        { print "usage: " USAGE > "/dev/stderr"; exit 1; }
      LCTX = CTX; RCTX = CTX;
    }
  else
    {
      if((LCTX == "") && (RCTX == "")) { LCTX = 0; RCTX = 0 }
    }
  LPAD = ""; for (i=0;i<LCTX;i++) LPAD = (LPAD "_")
  RPAD = ""; for (i=0;i<RCTX;i++) RPAD = (RPAD "_")
}

/./ {
   str = $0
   while (length(str) > 0)
     { match(str, PAT);
       if (RSTART == 0) break;
       if (RLENGTH == 0) 
         { printf "pattern /%s/ matches zero characters", PAT > "/dev/stderr"
           exit 1 
         }
       print substr((LPAD str RPAD), RSTART, LCTX + RLENGTH + RCTX)
       str = substr(str, RSTART+RLENGTH)
     }
   next
 }

/^$/ { next }