pro mk_syn_sfc, index_in, index, syn_sfc, exp_dur=exp_dur, inside=inside, $
                synstatus=synstatus
;+
;NAME: 
;         mk_syn_sfc.pro
;
;PURPOSE:
;         Create a synthetic Yohkoh-SFC for a given time and pointing,
;         as determined by the input index file.  The synthetic SFC is
;         generated by a linear interpolation of nearby SFC's.  This
;         routine can be very slow since it must read in the nearby SFC
;         database and operate on it.  The first call for a filter failure
;         epoch will be the slowest, subsequent calls will be somewhat 
;         faster as the SFC data are stored.
;
;CALLING SEQUENCE:
;         mk_syn_sfc, index_in, index, syn_sfc
;         mk_syn_sfc, index_in, index, syn_sfc, exp_dur=exp_dur
;
;INPUT:
;         index_in - index file, or array of index files (all from
;                    a single filter failure epoch) that is used
;                    to determine the date, x and y coordinates of  
;                    sun-center, and roll of the image.
; 
;OPTIONAL KEYWORD INPUT:
;         exp_dur -  Exposure duration for synthesized SFC.  The default
;                    exposure duration is 2691.09.         
;        
;OUTPUT:  
;         index -    The index_in values modified to indecate that the file
;                    is a synthetic SFC, with an exposure time. NOT YET 
;                    IMPLEMENTED.
;
;         syn_sfc -  The synthetic SFC, a 512x512 real-number array.
;KEYWORD OUTPUT:
;         inside - Boolean array, 1 = the SFC was interpolated, 
;                                 0 = the SFC was extrapolated.
;         synstatus - true (1) if synthetic generated ok
;
;HISTORY:
;
;V. 1.00  Written 08-Mar-2002 T. Metcalf 
;         This is a new version only loosely based on the old
;         mk_syn_sfc.pro.
;-

;Declare a common block to minimize reads of SFC data
common mk_syn_sfc_blk, roadmap, files, sssave, isfc, dsfc

;Initalize relevant parameters: filter a, filter b, x, y, roll, 
;solar diameter, exposure duration
filt_a      = gt_filta(index_in)
filt_b      = gt_filtb(index_in)
xy_param    = sxt_cen(index_in, roll=roll)
x_term      = xy_param(0,*)
y_term      = xy_param(1,*)
roll_term   = roll
solard_term = (get_sun(index_in))(1,*)
IF (1-keyword_set(exp_dur)) THEN exp_dur = 2691.09; TODO! pick a better number.

synstatus = intarr(n_elements(index_in)) & synstatus[*]=0
inside = synstatus

;Test that all SFC being generated will be from the same
;filter failure epoch.
epoch_date  = gt_day(index_in(0),/str)
epoch_bound = [get_yo_dates(/launch),get_yo_dates(/entrance),ut_time(!stime)]
t_compare   = ssw_time_compare(epoch_bound, epoch_date, /later)
later     = where((t_compare eq 1), num_gd_later)
epoch= later(0)-2

;Test that all index records are from the same epoch.
epoch_test = gt_day(index_in) ;TEST LIMITS!!!
temp_bound=intarr(n_elements(epoch_bound))
FOR i=0,n_elements(temp_bound)-2  DO BEGIN
   x_tmp=where((epoch_test gt gt_day(epoch_bound(i))) $
      and (epoch_test lt gt_day(epoch_bound(i+1))),num_good)
   temp_bound(i) = num_good
ENDFOR
y_tmp = where(temp_bound GT 0, num_gt_zero)
IF (num_gt_zero GT 1) THEN BEGIN $
   MESSAGE, 'Index_in files must be from the SAME filter failure epoch.'
   RETURN
ENDIF

estart = where(temp_bound GT 0)  ; Start of the epoch
entrance = [epoch_bound[estart],epoch_bound[estart+1]]  ; time range of this epoch

if n_elements(roadmap) LE 0 then begin  ; Read the SFC roadmap, if not already done
   sfcdir = get_logenv('DIR_SXT_SFC')
   files = findfile(sfcdir+'/sfc*')
   if files[0] eq '' then message,'No SFC files online in '+sfcdir
   rd_roadmap,files,roadmap
endif
ss = where(int2secarr(roadmap,entrance[0]) GT 0 AND $
           int2secarr(roadmap,entrance[1]) LT 0)
need_to_read = 0  ; check if we need to read the SFC images.
if n_elements(sssave) LE 0 then need_to_read = 1 $
else if n_elements(sssave) NE n_elements(ss) then need_to_read = 1 $
else if max(abs(ss-sssave)) NE 0 then need_to_read = 1
if need_to_read then begin  ; Read SFC's for this epoch if not already done
   if ss[0] LT 0 then message,'No SFC files for this epoch online in '+sfcdir
   if n_elements(dsfc) GT 0 then delvarx,dsfc  ; make some space
   message,/info,'Reading epoch '+entrance[0]+' to '+entrance[1]
   rd_xda,files,ss,isfc,dsfc
   sssave = ss
endif

;Construction of parameter vectors that are 
;derived from index_in values. (One vector for each index 
;of the index_in vector.)
param=fltarr(n_elements(index_in),3)
for k=0,n_elements(index_in)-1 do begin
      param(k, 0) = x_term(0,k)/solard_term(0,k)
      param(k, 1) = y_term(0,k)/solard_term(0,k)
      ;param(k, 2) = solard_term(0,k)
      ;param(k, 3) = (x_term(0,k))^2
      ;param(k, 4) = (y_term(0,k))^2
      ;param(k, 5) = (solarD_term(0,k))^2
      ;param(k, 6) = (x_term(0,k))*(y_term(0,k))
      ;param(k, 7) = (x_term(0,k))*(solarD_term(0,k))
      ;param(k, 8) = (y_term(0,k))*(solarD_term(0,k))
      ;param(k, 9) = (x_term(0,k))^3
      ;param(k, 10) = (y_term(0,k))^3
      ;param(k, 11) = (solarD_term(0,k))^3
      ;param(k, 12) = (x_term(0,k))^2*y_term(0,k)
      ;param(k, 13) = (x_term(0,k))*(y_term(0,k))^2
      ;param(k, 14) = (x_term(0,k))^2*(solarD_term(0,k))
      ;param(k, 15) = (x_term(0,k))*(solarD_term(0,k))^2
      ;param(k, 16) = (y_term(0,k))^2*(solarD_term(0,k))
      ;param(k, 17) = (y_term(0,k))*(solarD_term(0,k))^2
endfor

;Temporary array to hold the vector of synthetic 
;SFCs to be constructed. (One synthetic SFC for 
;each index of the index_in vector.)
syn_sfc = fltarr(512,512,n_elements(index_in))

;Calculate the inner product of the coefficient matrices
;with the parameter vectors derived from the index_in index
;records for each index element.
for k=0,n_elements(index_in)-1 do begin
   x = param(k, 0)
   y = param(k, 1)
   r = solard_term(0,k)
   ssfilt = where(gt_filta(isfc) EQ filt_a[k] AND $
                  gt_filtb(isfc) EQ filt_b[k],nssfilt)
   if nssfilt LE 0 then begin
      message,/info,'No SFCs with the right filter combination for ' + $
                    fmt_tim(index_in[k])+': skipping'
      synstatus[k] = 0
      inside[k] = 1
   endif else begin
      ; Get the coefficients of the interpolation
      coeff_s = mk_synsfc_coeff_restrict_2d(isfc[ssfilt],dsfc[*,*,ssfilt],x,y, $
                                         extrap=extrap)
      if strupcase(size(coeff_s,/tname)) EQ 'STRUCT' then begin
         for i = 0, 511 do begin
            for j = 0, 511 do begin
               syn_sfc[i,j,k] = total(coeff_s[1:*].coeff_vect[i,j]*param[k,*]) + $
                                       coeff_s[0].coeff_vect[i,j]
            endfor
         endfor
         if NOT extrap then begin
            synstatus[k] = 1
            inside[k] = 1
         endif else begin
            message,/info,'Extrapolating '+fmt_tim(index_in[k])
            synstatus[k] = 1
            inside[k] = 0
         endelse
      endif else begin
         message,/info,'Could not interpolate '+fmt_tim(index_in[k])+': skipping'
         synstatus[k] = 0
         inside[k] = 1
      endelse
   endelse
endfor

;Construct vector of index records for vector of constructed
;synthetic SFCs by modifying exposure duration, and signaling
;synthetic SFC entry. CURRENTLY UNIMPLEMENTED!!! 
index = index_in 

; S.L.Freeland - 18-Sep-2000 - add some history information
his_index,index,/enable
index.sxt.imgparam=1
index.his.pixel_size=1
index.sxt.shape_cmd=[512,512]
index.sxt.shape_sav=[512,512]
index.his.expdur=exp_dur

;Give the synthetic SFC a 'pseudo' exposure time.  Default = 2691.09
syn_sfc=syn_sfc*exp_dur 

if n_elements(synstatus) EQ 1 then synstatus = synstatus[0] ; make scalar

end
