pro search, file, string, window=window, case_ignore=case_ignore, ss=ss, $
	delimit=delimit, outarr=outarr, first=first, last=last, quiet=quiet
;
;+
;   Name: search
;
;   Purpose: emulate VMS search utility 
;
;   Input Parameters:
;      file -   file to search (can be string array also)
;      string - string to search for
;
;   Keyword Parameters:
;      window - number of lines above/below matches to display 
;      case_ignore - force search to be case insensitive
;
;   Calling Sequence:
;      search, file, string [, window=[above,below], /case_ignore]
;      search, file, string, window=delta
;      search, array, string
;
;   History:
;      15-Apr-1994 (SLF) Written (uses rd_tfile and wc_where)
;      18-Apr-1994 (SLF) Minor change to delimit logic
;      22-Apr-1994 (SLF) Allow string array, add FIRST and LAST keywords
;-

if n_params() ne 2 then begin
   message,/info,'Calling Sequence:  '
   message,/info,'IDL> search, file, string [window=[above,below], /case_ignore]
   return
endif

loud=1-keyword_set(quiet)

sfile=file
sstring=string

if not keyword_set(delimit) then delimit='-'
del=string(replicate((byte(delimit))(0),80))

lstring=strlen(string)
show=string(replicate((byte('*'))(0),lstring))

; input may be string array or file
if file_exist(sfile(0)) then contents=rd_tfile(sfile(0)) else contents=sfile

lastline=n_elements(contents)-1

if not keyword_set(window) then wind=[0,0] else wind=window
if data_chk(window,/scaler) then wind=replicate(window,2)

find=wc_where(contents,'*' + sstring(0) + '*', wccnt, case_ignore=case_ignore)
case 1 of
   keyword_set(first): find=find(0)
   keyword_set(last): find=find(n_elements(find)-1)
   else:
endcase
wccnt=n_elements(find) < wccnt 

ss=-1
if wccnt eq 0 then message,/info,'String not found' else begin
   outarr=''
   ss=find
   locexe=['strpos( match, sstring )', $
           'strpos(strlowcase(match),strlowcase(sstring))']
   for i = 0,wccnt-1 do begin
;     ----------- highlight position ------------------
      match=contents(find(i))
      delim=string(replicate(32b, strlen(match) > 78))
      exestat=execute('wcloc=' + locexe(keyword_set(case_ignore)))
      if wcloc ne -1 then strput,delim,show,wcloc
;     ------------------------------------------------
      startt=find(i) - wind(0) > 0
      stopp=find(i) + wind(1) < lastline
      lines=lindgen( (stopp-startt) > 1) + startt 
      dlines=[contents(startt:find(i)), delim, $
	      contents((find(i)+1)<stopp:stopp)  ]
      dlines=dlines(uniqo(dlines))
      outarr=[outarr,del,dlines,del,'']
   endfor
   outarr=outarr(1:*)
   if loud then prstr,outarr
   endelse

return
end
