
function scc_time2tlmfile,ts,te,sc, dir=dir, nrl=nrl,n_per_day=npd

;+
; $Id: scc_time2tlmfile.pro,v 1.3 2010/12/09 22:34:36 nathan Exp $
;
; Project : STEREO SECCHI
;
; Name    : scc_time2tlmfile
;
; Purpose : given a time range, returns paths to appropriate level 0
;           telemetry files
;
; Use     : IDL> 
;
; Inputs  :
;    ts = start time, anytim format
;    te = end time
;    sc	    STRING  representing which STEREO spacecraft
;
; Outputs :
;    f = file names (paths)
;
; Keywords:
;    n_per_day = number of files covering each day.
;                Default is 6 (appropriate for secchi),
;                but reverts to 1 if there's consistently only 1/day
;    dir = directory to search in
;    /NRL   Assume NRL directory tree
;
; Common  : None
;
; Restrictions:
;
; Side effects:
;
; Category    : Pipeline
;
; Prev. Hist. :
;
; Written     : Jean-Pierre Wuelser, LMSAL, 7-Nov-2006
;               JPW, 24-Jan-2007 : now handling mix of .fin and .ptp files
;
; $Log: scc_time2tlmfile.pro,v $
; Revision 1.3  2010/12/09 22:34:36  nathan
; finish implementation
;
; Revision 1.2  2007/01/25 16:31:17  euvi
; now handling both .fin and .ptp files
;
;-

if strlowcase(strmid(sc,0,1)) eq 'a' then obs='ahead' else obs='behind'

IF ~file_exist('/net/kokuten') THEN nrl=1
; step through days and retrieve files for each day

uts=anytim2utc(ts)
ute=anytim2utc(te)
ut=uts
ff=''
FOR i=uts.mjd,ute.mjd DO BEGIN
    ut.mjd=i
    IF keyword_set(DIR) THEN dir1=dir ELSE $
    IF keyword_set(NRL) THEN dir1=get_att_dir(ut,sc, YEAR=yyyy) ELSE $
    dir1='/net/kokuten/archive/stereo/telemetry/'+obs+'/secchi'
    doy=string(utc2doy(ut),'(i03)')
    ff1 = file_search(concat_dir(dir1,'secchi_'+obs+'_'+yyyy+'_'+doy+'*.fin'))
    if ff1[0] ne '' then ffi=ff1 ELSE begin
    	ff2 = file_search(concat_dir(dir1,'secchi_'+obs+'_'+yyyy+'_'+doy+'*.ptp'))
    	if ff2[0] ne '' then ffi=ff2 else ffi=''
    endelse
    IF (ffi[0] NE '') THEN IF (i EQ uts.mjd) THEN ff=ffi ELSE ff=[ff,ffi]
ENDFOR

IF ff[0] EQ '' THEN message,'No level_0_telemetry files found.'

yr  = strmid(ff,16,4,/reverse_offset)
doy = strmid(ff,11,3,/reverse_offset)
num = strmid(ff,7,1,/reverse_offset)
; typ is '1' for .fin files, '0' for .ptp :
typ = strtrim(string(fix(strmid(ff,2,3,/reverse_offset) eq 'fin')),2)
; append version string to typ
typ = typ+strmid(ff,5,2,/reverse_offset)

if n_elements(npd) eq 0 then if max(num) eq 1 then npd=1 else npd=6
tfil = 24d0*3.6d3/npd                                ; seconds/file

tfe = anytim(doytim2ints(doy,yr))+tfil*double(num)   ; end times of files
tfs = tfe - tfil                                     ; start times of files
ww = where(tfe gt anytim(ts) and tfs le anytim(te),nww)
if nww eq 0 then return,''
ff = ff[ww]
typ= typ[ww]

ydn  = strmid(ff,16,10,/reverse_offset)              ; year_doy_num
ydnv = ydn+typ                                       ; year_doy_num_typ_ver
ff   = ff[uniq(ydn,sort(ydnv))]                      ; only the last version

return,ff

end
