;+
;$Id: sccfindfits.pro,v 1.8 2013/11/22 22:31:10 thompson Exp $
;
; Project     :	STEREO - SECCHI
;
; Name        :	SCCFINDFITS()
;
; Purpose     :	Find SECCHI FITS data files.
;
; Category    :	SECCHI, Filename
;
; Explanation : Given one or more SECCHI FITS filenames, this routine returns
;               the full path to those files within the SECCHI FITS data tree.
;               First, the filename is parsed to determine the date,
;               spacecraft, and telescope.  Then, the standard SECCHI tree is
;               searched to find the file.  The routine looks first in the "lz"
;               tree, then in "pb", and finally "rt".
;
; Syntax      :	Path = SCCFINDFITS( FILENAME )
;
; Examples    :	Image = SCCREADFITS( SCCFINDFITS('20061109_224438_k4c1B.fts') )
;
; Inputs      :	FILENAME = An array of file names to look for.
;
; Opt. Inputs :	None
;
; Outputs     :	The result of the function is the path to the file.
;
; Opt. Outputs:	None.
;
; Keywords    :	BEACON = Look in the beacon directories (SSC only)
;
; Env. Vars.  : See SCC_DATA_PATH
;
; Calls       :	FILE_EXIST, BREAK_FILE, SCC_DATA_PATH, CONCAT_DIR, ALL_VALS
;
; Common      :	None.
;
; Restrictions:	None.
;
; Side effects:	None.
;
; Prev. Hist. :	None.
;
; $Log: sccfindfits.pro,v $
; Revision 1.8  2013/11/22 22:31:10  thompson
; Added keyword ERRMSG
;
; Revision 1.7  2013/04/25 16:15:14  mcnutt
; corrected .fts ext check to work with an array
;
; Revision 1.6  2013/02/21 20:11:14  thompson
; *** empty log message ***
;
; Revision 1.5  2012/07/27 19:40:31  nathan
; try ? in level-char of filename
;
; Revision 1.4  2011/09/19 22:34:50  nathan
; search cal last instead of first
;
; History     : Version 1, 15-Nov-2006, William Thompson, GSFC
;   	    	Version 2, 08-Apr-2009, WTT, added keyword BEACON
;   	    	Version 3, 13-Nov-2009, NRich, on error return '' 
;               Version 4, 21-Feb-2013, Only call message with first bad name
;               Version 5, 22-Nov-2013, WTT, pass ERRMSG to SCC_DATA_PATH
;
; Contact     :	WTHOMPSON
;-
;
function sccfindfits, filename, beacon=beacon, errmsg=errmsg
on_error, 2
;
;  Create an empty RESULT array with the same dimensions as the input array.
;
sz = size(filename)
if sz[0] eq 0 then result = '' else result = strarr(sz[1:sz[0]])

;
;  Test for names which are already completely specified.
;
w = where(file_exist(filename), count)
if count gt 0 then result[w] = filename[w]
;
;  Parse the filenames to extract the date, telescope, and spacecraft.
;
break_file, filename, disk, dir, name, ext
fcheck=where(ext ne '.fts',cnt)
if cnt gt 0 then begin
  tmp=filename[fcheck]
  strput,tmp,'.fts',strpos(tmp[0],'.')
  filename[fcheck]=tmp
endif
w = where(strlen(name) ne 21, count)
if count gt 0 then BEGIN
    message, name[w[0]]+ext[w[0]]+': Unrecognized filename',/info
    return,''
ENDIF
date = strmid(name,0,8)
tel = strmid(name,18,2)
sc = strmid(name,20,1)
;
;  Convert the 2-digit telescope codes in the filename into the appropriate
;  directory names.
;
in  = ['c1',   'c2',   'eu',   'h1',   'h2']
out = ['cor1', 'cor2', 'euvi', 'hi_1', 'hi_2']
total = 0
for i=0,4 do begin
    w = where(tel eq in[i], count)
    if count gt 0 then tel[w] = out[i]
    total = total + count
endfor
if total ne n_elements(filename) then BEGIN
    message, name[w[0]]+ext[w[0]]+': Unrecognized filename',/info
    return,''
ENDIF
;
;  Find all instances of DATE, TEL, and SC.
;
dates = all_vals(date)
tels  = all_vals(tel)
scs   = all_vals(sc)
;
;  Define the possible sources and types.
;
sources = ['lz', 'pb', 'rt']
types = ['img', 'seq','cal']
;
;  Step through the sources and types.
;
for isource = 0,2 do begin
    source0 = sources[isource]
    for itype = 0,2 do begin
        type0 = types[itype]
;
;  Check to see which filenames are not yet filled in.  If done, jump directly
;  to the end.
;
        isblank = result eq ''
        nblank = total(isblank)
        if nblank eq 0 then goto, finish
;
;  Step through the spacecraft, dates, and telescopes, and determine which
;  filenames with unfilled paths correspond to that combination.
;
        for isc = 0,n_elements(scs)-1 do begin
            sc0 = scs[isc]
            for idate = 0,n_elements(dates)-1 do begin
                date0 = dates[idate]
                for itel = 0,n_elements(tels)-1 do begin
                    tel0 = tels[itel]
                    w = where((sc eq sc0) and (date eq date0) and $
                              (tel eq tel0) and isblank, count)
;
;  Form the path out of the selected combination, and see which files are found
;  there.
;
                    if count gt 0 then begin
                        path0 = scc_data_path(sc0, date=date0, telescope=tel0, $
                                             source=source0, type=type0, $
                                             beacon=beacon, errmsg=errmsg)
                        if n_elements(errmsg) gt 0 then $
                          if errmsg ne '' then begin
                            print, errmsg
                            return, ''
                        endif
                        path = concat_dir(path0, filename[w])
;
;  Try both with and without a .fts extension.
;

                        ww = where(file_exist(path), count)
                        if count gt 0 then result[w[ww]] = path[ww] ELSE BEGIN
			    fn2=filename[w]
			    strput,fn2,'?',16
			    path = concat_dir(path0, fn2)
    	    	    	    ww = where(file_exist(path), count)
			    if count gt 0 then result[w[ww]] = path[ww]
			ENDELSE
                        path = path + '.fts'
                        ww = where(file_exist(path), count)
                        if count gt 0 then result[w[ww]] = path[ww]
;
                    endif       ;count gt 0
                endfor          ;itel
            endfor              ;idate
        endfor                  ;isc
    endfor                      ;itype
endfor                          ;isource
;
;  Exit point.  Return the result array.
;
finish:
return, result
end
