;+
;
; NAME: BUILD_FNAME
;
;
; PURPOSE: Construct filenames from templates and replacement strings.
;
;
; CATEGORY: i/o, file management
;
;
; CALLING SEQUENCE: fname=build_fname(template, wildcard, inserts)
;		    e.g.
;		    fname= build_fname('SHER_IBDB_%_%.FITS','%',['0','1398'])
;		    PRINT,FNAME
;		    SHER_IBDB_0_1398.FITS
;
; CALLED BY: SPEX MENU
;
;
; CALLS TO: standard idl
;
; INPUTS:
;       template - string including wildcards for replacement
;	wildcard - string indicating replacement position
;	inserts  - string(s) to replace wildcards with, no action on ''
;	/upcase  - force all strings to uppercase
;	/lowcase - force all strings to lowercase
;
; PROCEDURE:
;	uses strpos and strmid to substitute for each wildcard in turn
;	works only on scalar strings
;
; MODIFICATION HISTORY: ras, 18-jan-94
;
;-

function build_fname, template, wildcard, inserts, upcase=upcase, $
	lowcase=lowcase

temp = template
wild = wildcard
ins  = inserts

if keyword_set(upcase) then begin
	temp = strupcase(temp)
	wild = strupcase(wild)
	ins  = strupcase(ins )
endif

if keyword_set(lowcase) then begin
	temp = strlowcase(temp)
	wild = strlowcase(wild)
	ins  = strlowcase(ins )
endif

wi = where(inserts ne '',ni)
if ni eq 0 then return, temp
inserts = inserts(wi)

lw = strlen(wild(0))

for i=0,ni-1 do begin
	len = strlen(temp)
	pos = strpos(temp, wild(0))
	if pos ge 0 then temp= strmid(temp,0,pos)+ ins(i)+ strmid(temp,pos+lw,len)
endfor

return, temp
end
