;+
; NAME:
;        sb_filesearch
; PURPOSE:
;        returns filenames from a prioritized search in given path(s)
; CATEGORY:
;        image processing, widgets
; CALLING SEQUENCE:
;        ff = sb_filesearch(path,pattern,timerange=[ts,te])
; INPUTS:
;        path = string element
;        pattern = string element
; KEYWORDS (INPUT):
;        timerange = [ts,te].  ts,te : anytim compatible format (except ext)
;        /year2digit : do subdirectory search in yymmdd instead of yyyymmdd
;                      also prevents subselection of filenames by date
; OUTPUTS:
;        ff : vector of file names
; KEYWORDS (OUTPUT):
; COMMON BLOCKS:
; SIDE EFFECTS:
; RESTRICTIONS:
; PROCEDURE:
;   Search is performed in the following order:
;     1. Search for pattern in appropriate subdirectories of path  named
;        yyyymmdd (or yymmdd if /year2digit is set)
;     2. If nothing found, search for pattern in path (non-recursive)
;     3. If nothing found, search for '*' in path (non-recursive)
;   If something was found: try to subselect for timerange (if present):
;     1. If file2time returns something, do the subselect even if result empty
;     2. If file2time returns no valid time, do not subselect
; MODIFICATION HISTORY:
;        JPW, 6/26/2007
;-
FUNCTION sb_filesearch,path,patt,timerange=tran,year2digit=y2dig,outt=tt
ff = ''
; check in potential subdirectories by date
if n_elements(tran) eq 2 then begin
  ts = anytim(tran[0])
  te = anytim(tran[1])
  tdrs = [anytim(timegrid(ts,te,/days)),te]
  dirs = time2file(tdrs,/date_only,year2digit=y2dig)
  dirs = dirs(uniq(dirs))          ; unique names only
  dirs = concat_dir(dirs,patt)     ; add pattern
  dirs = concat_dir(path,dirs)     ; add path
  ff = file_search(dirs)
endif
; if nothing found (or no timerange given), look in simple path+pattern
if ff[0] eq '' then ff=file_search(concat_dir(path,patt))
; if still nothing found, ignore pattern:
if ff[0] eq '' then ff=file_search(concat_dir(path,'*'))
; check if we can subselect by time using file2time:
if ff[0] ne '' && n_elements(tran) eq 2 && ~keyword_set(y2dig) then begin
  tt = file2time(ff,out_style='sec')
  siz = size(tt)
  if siz[siz[0]+1] eq 5 then if max(tt) gt 1d4 then begin
    w = where(tt ge ts and tt le te,nw)
    if nw gt 0 then begin
      ff=ff[w]
      tt=tt[w]
    endif else begin
      ff=''
      tt=0d0
    endelse
  endif else tt=dblarr(n_elements(ff))
endif
return,ff
end