;+
; PROJECT:
;	SDAC
; NAME:
;       FLARE_F_NAME
;
; PURPOSE:
; 	This procedure finds the data file (fdb, cont, or discsp) for a requested flare.
;
; CATEGORY:
;       BATSE
;
; CALLING SEQUENCE:
;	flare_f_name, flare, dd_open, filename, error=error
;
; CALLS:
;	none
;
; INPUTS:
;   flare_n    - (input)  flare number for which to find file
;   dd_open    - (input)  dd_open.type contains type of file to find: 1/2/3 = fdb/cont/discsp
;
; OPTIONAL INPUTS:
;	none
;
; OUTPUTS:
;   filename   - (output) string containing file name found for flare
;
; OPTIONAL OUTPUTS:
;	none
;
; KEYWORDS:
;   error      - (output) =1 if error finding file for flare, 0 otherwise
; COMMON BLOCKS:
;	none
;
; SIDE EFFECTS:
;	none
;
; RESTRICTIONS:
; Can't use this for bdb files because they don't have the flare number
; in the file name.  For bdb files, FIND_DBFILE gets the time for the
; flare and then calls TIME_F_NAME.
;
;
; PROCEDURE:
;	none
;
; MODIFICATION HISTORY:
; Kim Tolbert
;  Mod 4/27/95 by AES - added ending check to accommodate different
;	file endings (i.e ';','.',' ') across platforms and avoid
;	getting wrong flare through flarenum* scenario
;  ras, 19-jun-95, used break_file to parse out filename
;	richard.schwartz@gsfc.nasa.gov, 9-oct-1997, cleaned bug in
;	file selection and default to highest version number on multiple versions.
;	2-aug-2001 ras, modified search strings,
;-
pro flare_f_name, flare_n, dd_open, filename, error = error
;


error = 0

if (dd_open.type lt 0) or (dd_open.type gt 3) then begin
   print, 'FLARE_F_NAME:  Invalid type of data requested.'
   goto, error_exit
endif

filetype = ['BDB', 'FDB', 'CONT', 'DISCSP']
ftype = filetype(dd_open.type)

batse_dir = 'BATSE_' + ftype
ending=[';*','','.*']
;if !version.os ne 'vms' then batse_dir = chklog(batse_dir)
batse_dir = (chklog(batse_dir))(0)

;strflare_n=strtrim(string(flare_n),2)
strflare_n=strtrim(flare_n,2)
if ftype ne 'BDB' then begin
for i=0,n_elements(ending)-1 do begin
   base_search_name = '*.' + strlowcase(ftype) + $
       '_' + strflare_n
   search_name =  base_search_name + ending(i)
   file_arr = loc_file(path=batse_dir, search_name ,count=count)
   if count ne 0 then file_arr = $
   file_arr(wc_where(strlowcase(file_arr), $
			       strlowcase(base_search_name)+'*', count))

   if count ne 0 then goto,foundfile
endfor

foundfile:
	case count of

	0 : begin
      		print,'Could not find ', filetype(dd_open.type), $
			' file for flare ',flare_n
      		goto, error_exit
    	    end
	else:begin
      		break_file, file_arr(count-1), disk_log, dir, filnam, ext
		filename = filnam + ext

		;brack = strpos(file_arr(0),']') + 1
      		;new_name = strmid(file_arr(0), brack, 50)
      		;filename = strtrim(new_name,2)
     	      end
	endcase

endif else begin
   read_flare, flare_n, fl_structure
   parse_atime, fl_structure.start_secs, year=year, month=month, day=day, /st
   filename = year+month+day+'.bdb'
endelse

goto, getout

error_exit:
error = 1

getout:
return & end
