function imginfo, index, sec2sunset
;
;   Name: imginfo
;
;   Purpose: summary info for input text , return sec2sunset
;
tim2orbit,index,tim2night=tim2night      
sec2sunset=tim2night*60
info=[fmt_tim(index),strtrim(gt_filta(index,/string),2) + '/' +  gt_filtb(index,/str),$
      gt_dpe(index,/string), $
      string(index.his.sun_center(0:1),format='(f8.2,"(X)",f8.2,"(Y)")'), $
      string(sec2sunset,format='(f5.1)') + ' S.']
info=arr2str(info,' ')
return,info
end
; ------------------------------------------------------

pro mk_sfc, week, online=online, sftdir=sftdir, sfcdir=sfcdir,              $
   noconfirm=noconfirm, min_sep=min_sep, no_mail=no_mail, testing=testing,  $
   sfcs_added=sfcs_added, tim2sunset=tim2sunset, check_params=check_params, $
   param_file=param_file
;+
;   Name: mk_sfc
;
;   Purpose: convert one or more SFT files to SFC files (via sfc_prep)
;
;   Input Parameters:
;      week - week string(s) in form YY_WW 
;
;   Calling Sequence:
;      mk_sfc, week_str [param_file='filename', /check_param, /online, $
;	                 /noconfirm, /testing, /no_mail ]
;
;   Calling Examples:
;      mk_sfc,'95_50',/online,/noconfirm   ; process SFTs for 95_50
;      mk_sfc,/check_param		   ; just show current parameter
;					   ; settings (show param file)
;  
;   Optional Keyword Parameters:
;      online - if set, put the sfcs online (DIR_SXT_SFC)
;      noconfirm - if set, dont prompt for sfc/sft dirs
;      sftdir - if set, alternate sft output directory
;      sfcdir - if set, alternate sfc output directory 
;      no_mail - if set, dont send mail
;      check_params - if set, just show current SFC parameter values
;      param_file - optional SFC parameter file (Def: $ys/sxt/doc/mk_sfc.param)
;
;   History:
;      4-may-1995 (SLF) - Archive version (from orig written 15-mar)
;                         Add auto-update, auto-mail, time window
;     29-Jun-1995 (SLF) - write log to DIR_SITE_LOGS (not REFORMAT_SC)
;     23-aug-1995 (SLF) - add Leak ERA criteria 
;      8-nov-1995 (SLF) - DPE filter , use parameter file for DPE, seperation
;			  add CHECK_PARAMS keyword (verify param table)
;     18-dec-1995 (SLF) - parameterize Tim2Sunset (in param table)
;      9-jan-1995 (SLF) - fix status messages
;     16-apr-1996 (SLF) - update documentation header, add PARAM_FILE keyword
;     21-may-1996 (SLF) - return with no action if NO SFTs found
;      3-mar-1997 (JRL) - Give the file date (not current date) if /check_param 
;     20-jan-1997 (SLF) - filter out all but half-res
;-
if not keyword_set(param_file) then $
   param_file=concat_dir(get_logenv('DIR_SXT_DOC'),'mk_sfc.param')

if not file_exist(param_file) then begin
   message,/info,"Cannot find parameter file: " + param_file
   return
endif

; read parameter file
params=rd_tfile(param_file,nocomment=';')
params= strcompress(/remove_all, $
 (str2cols(params(where(strcompress(params,/remove) ne ''))))(*,1:*))
if n_elements(tim2sunset) ne 2 then tim2sunset=[15,25]

;  build DPE execute lookup tables for output and execution
dpeopen= 'DPE (FiltA=Open)'
dpenuden='DPE (FiltA=NuDen)'
tim2suns=fltarr(2,5)

for i=0,4 do begin
   dpeopen=[dpeopen, gt2exe('dpe=' + params(1,i))] 
   dpenuden=[dpenuden,gt2exe('dpe=' +  params(2,i))]
   t2s=str2arr(params(4,i))
   if n_elements(t2s) eq 1 then t2s=str2arr(params(4,i),'-')
   tim2suns(0,i)=float(t2s)   
endfor

;exestr=tab(filtb,filta eq NuDen) 

dpe_exetab=[[str_replace(dpeopen, 'gt_dpe','gt_dpe(sftind)')],$
              [str_replace(dpenuden,'gt_dpe','gt_dpe(sftind)')]]		

minsep=float(params(3,*))

if keyword_set(check_params) then begin
   sp='  '
   nfil = file_info2(param_file, finfo2)
   outarr=strjustify(						$
      strjustify(['FiltB',reform(params(0,*))] ) + sp      + $
      strjustify(str_replace(dpeopen,'gt_','')) + sp + $
      strjustify(str_replace(dpenuden,'gt_')) + sp  + $
      strjustify(['Dlt-Pnt',strjustify(reform(params(3,*)))+'"'],/right) + sp + $
      strjustify(['Tim2Sun',string(fix(tim2suns),format="(i2,'-',i2)") ]),/box)
   more,["------ mk_sfc parameters at "+ fmt_tim(finfo2) + " ------","",	$
         "","Parameters from file: " + param_file + "..." ,outarr]
   return
endif

mailit=1-keyword_set(no_mail)
testing=keyword_set(testing)

sfc_mail=get_logenv('MAIL_SXT_SFC')			;mail users list
if not keyword_set(sfc_mail) then $
   sfc_mail=(["software@isass0,sxt_co@isass0","freeland@isass0"])(testing)

if not keyword_set(min_sep) then begin
   min_sep=get_logenv('SXT_SFC_MINSEP')
   if not keyword_set(min_sep) then min_sep=10.		; arcseconds
endif else message,/info,"MIN_SEP keyword not supported (now uses parameter file)"
							; parameter
noconfirm=keyword_set(noconfirm) or get_logenv('ys_batch') ne ''

if n_params() eq 0 then begin
   tbeep
   message,/info,"Must supply input week(s),  returning..."
   return
endif

if keyword_set(online) then begin
   sfcdir=get_logenv('DIR_SXT_SFC')
   sftdir=get_logenv('DIR_SXT_SFT')
endif

if not keyword_set(sfcdir) then begin
   tbeep
   message,/info,"please specify SFC output directory (or use /online)
   return   
endif

if not keyword_set(sftdir) then sftdir=get_logenv('DIR_SXT_SFT')
resp=''

if not keyword_set(noconfirm) then begin
   prstr,['Using directories...','   Input  (SFT): ' + sftdir,	$
				 '   Output (SFC): ' + sfcdir,'']
   read,"Enter <ok> to continue, anything else to quit: " ,resp
   if strupcase(resp) ne 'OK' then message,"Aborting on request..."
endif else $
   prstr,['Using directories...','   Input  (SFT): ' + sftdir,	$
			         '   Output (SFC): ' + sfcdir,'']

sfts=file_list(sftdir,'sft' + week  + '.??')
if sfts(0) eq '' then begin
   message,/info,"NO sft files found..."
   return
endif

; loop logic not terribly efficient (reread sfc index every sft), but simple
;  
user=get_user()
sfcs_added=lonarr(n_elements(sfts))

; SLF 24-aug-1995 - add Leak-Era primary selection filter

ranges=[get_yo_dates(/entrance),fmt_tim(ut_time())]	; entrance filt changes

for i=0,n_elements(sfts)-1 do begin			; for each sft file
;  maintain status file
   mfile=concat_dir('$DIR_SITE_LOGS','mk_sfc_' + user + '.' + week(i))
   pr_status,txt,/idldoc
   file_append,mfile,txt,/new				; start status
   file_append,mfile,['','----------- SFT File: ' + sfts(i) + '-----------','']
; 
   rd_sda,sfts(i),-1,sftind,/nodata			; input current sft ind

tsec = int2secarr(sftind)
ind_start = (sftind(where(tsec eq min(tsec))))(0)
ind_end = (sftind(where(tsec eq max(tsec))))(0)
t_start = anytim2ints(ind_start,off=-3600)
t_end = anytim2ints(ind_end,off=3600)
rd_att,t_start,t_end,data_att,/nearest
ss_match = tim2dset(data_att,sftind)
ss_good = where(data_att(ss_match).status1 eq 4, n_good)

   for j=0,n_good-1 do begin				; for each sft image
      rd_sda,sfts(i),ss_good(j),sftind,sftdata			; read an sft images
;     .......apply additional sft->sfc filters here....
      secs=int2secarr(anytim2ints(ranges),sftind)
      sftinfo=imginfo(sftind(0),sec2sunset)
;     get SFC info
      sfcs=file_list(sfcdir,'sfc??????.????')		; update sfc list
      sfcrng=(where(secs eq abs(secs)))(0)		; where positive
      noneyet=1						; assume no match

      if sfcs(0) ne '' then begin
         rd_sda,sfcs,-1,sfcind,/nodata			; input sfc indices   
         sfcss=sel_timrange(sfcind,ranges(sfcrng-1),ranges(sfcrng),/bet)
         noneyet=sfcss(0) eq -1
      endif

      resok=gt_res(sftind) eq 1

      sunok=sec2sunset ge tim2suns(0,gt_filtb(sftind)-2) and $
         sec2sunset le tim2suns(1,gt_filtb(sftind)-2)

      dpeexe=execute('dpeok=' + $
         dpe_exetab(gt_filtb(sftind)-1, gt_filta(sftind,/string) eq "NuDen"))

      if sunok and dpeok and resok then begin
;        use match index to get pointing seperation		
         msep=(minsep((gt_filtb(sftind)-2)>0))(0)	; align
         pdelta=msep + 1.
         mess= [ $
	    'SFC ERA >>>> From: ' + ranges(sfcrng-1) + ' To: ' + ranges(sfcrng), $
            'CURRENT SFT> ' + sftinfo, 	$
            'Minimum Pointing seperation = ' + strtrim(msep(0),2)]
         matches=-1
         if not noneyet then $			; check closest pointing
            matches=match_index(sftind,sfcind(sfcss),/point,pdelta=pdelta)
         case 1 of
            noneyet: sfcmess=' NO SFCS for this ERA'
            matches(0) eq -1: sfcmess=' NO SFCS with for this Filter configuration'
            else: sfcmess=imginfo(sfcind(sfcss(matches(0))))                  
         endcase
            mess=[mess, 'CURRENT SFC> ' + sfcmess]

         prstr,mess
         file_append,mfile, mess
         if pdelta(0) gt msep or matches(0) eq -1 then begin			; add image
            outsfc=concat_dir(sfcdir,'sfc' + (ex2fid(anytim2ex(sftind)))(0))
	    pmess="POINTING SEPERATION (SFT:SFC) : " + $
               strtrim(pdelta(0),2) + " arcseconds"
            mess=[pmess,'NO GOOD MATCH FOR THIS SFT - ADDING TO SFC DATA BASE', $	
                  'NEW SFC FILENAME >>> ' +  outsfc ]            
            mess=[strjustify(mess,/box),'']
            prstr,mess
            file_append,mfile,mess
            sfc=sfc_prep(sftind,sftdata)
            sfcs_added(i)=sfcs_added(i)+1
            if not testing then sav_sda, outsfc, sftind, sfc
         endif else begin					; reject image
            mess=['Existing SFC match is ok, nothing added','']
            prstr,mess
            file_append,mfile,mess
         endelse
      endif else begin
         mess = ['CURRENT SFT> ' + sftinfo, $
            'Rejected: SFT outside SFC ' + $
               (['time','dpe'])(1-dpeok) + ' window, nothing added','']
         prstr,mess
         file_append,mfile,mess
      endelse
   endfor						; end image loop
   if mailit then begin
      subject='mk_sfc for week: ' + week(i) + ' #NEW: ' + $
         strtrim(sfcs_added(i),2)      
      mail,file=mfile,subj=subject,/no_defsubj,user=sfc_mail
   endif
endfor								; end sft loop

return
end
