PRO xrt_synleaksub, in_idx, in_da, out_idx, out_da, $
    kfact=kfact, leak_image=leak_image, verbose=verbose, qstop=qstop
; =========================================================================
;+
; PROJECT:
;       Solar-B / XRT
;
; NAME:
;
;       XRT_SYNLEAKSUB
;
; CATEGORY:
;
;       Data calibration.
;
; PURPOSE:
;
;       Subtract light leak (visible stray light) image from 
;       XRT synoptic composite images.
;
; CALLING SEQUENCE:
;
;       XRT_SYNLEAKSUB, in_idx, in_da, out_idx, out_da 
;                         [,kfact=kfact, leak_image=leak_image]
;
; INPUTS:
;
;       IN_IDX    - [Mandatory] (structure scalar)
;                   This is the "index" for a synoptic composite image.
;                   
;       IN_DA     - [Mandatory] (2D number array, [Nx,Ny])
;                   This is the 2D data array for the synoptic composite
;                   image.
;
; KEYWORDS:
;
;       KFACT    - [Optional] k-factor to apply when subtracting the light
;                  leak image:    out_da = in_da - k * [leak_img]
;                  1.0 is the default value.
;     LEAK_IMAGE - [Optional] (2D image array) Specify the leak image to 
;                  subtract, when you try a non-default image.
;                  1024x1024, prepped and exposure normalization assumed.
;      /VERBOSE  - [Optional] (Boolean) If set, print out extra messages.
;
; OUTPUTS:
;
;       OUT_IDX  - [Mandatory] (structure scalar)
;                  This is the "index" for the output image. It will
;                  have the same content as in_IDX (after it has been 
;                  through <xrt_prep.pro> and normalized), except that
;                  there will be an update to the HISTORY field.
;       OUT_DA   - [Mandatory] (2D number array, [Nx,Ny])
;                  This is the 2D data array after the light leak (stray
;                  light component) subtracted.
;
; EXAMPLES:
;
;       Basic usage:
;       IDL> file='./comp_XRT20200220_061539.6.fits'  ; sample Al_mesh image 
;       IDL> read_xrt, file, in_idx, in_da
;       IDL> xrt_synleaksub, in_idx, in_da, out_idx, out_da
;
; COMMON BLOCKS:
;
;       none
;
; NOTES:
;
;      1) XRT images obtained after 9-May-2021 suffer visible stray light
;         contamination (light leak) due to the pre-filter failure, i.e.
;         tiny rupture development occurred multiple times as follows.
;            phase 1 :  9-May-2012 12:00
;            phase 2 : 14-Jun-2015 12:30
;            phase 3 : 27-May-2017 11:00
;            phase 4 : 29-May-2018 00:00
;            phase 5 :  8-Jun-2022 12:40
;            phase 6 :  5-may-2023 04:30
;            phase 7 : 11-may-2024 06:15
; 
;      2) The light leak correction is done by simply subtracting the
;         light leak image (visible stray light component included in
;         each X-ray filter pair) obtained during the Hinode satellite's
;         eclipse season, which occurs roughly May to August each year. 
;         The light leak image has the following characteristics:
;       - Leak pattern and intensity differ with each filter and also
;         with the satellite pointing.
;       - Leak pattern and intensity of the same filter and pointing
;         are roughly constant during each stray light phase (above),
;         but vary by ~10% depending on the growth of the contamination
;         layer on the CCD (that repeats gradual increase and jump down
;         after CCD bakeouts).
;
;      3) The image for the light leak correction should therefore be
;         selected for the same filter, same satellite pointing, same
;         stray light phase then ideally be adjusted for the level of
;         CCD contamination at the time of observation.
;         However, as a practical matter, preparing the leak image
;         for every possible pointing is hard to achieve, while we
;         have good amount of light leak measurements at the disk
;         center pointing. The full-disk composite images are therefore
;         corrected most reliably for the light leak.
;
;      4) Intensity variation of the leak image due to the growth of CCD
;         contamination layer is well determined for Ti_poly at the
;         stray light phase 1 by using the intensity correlation between
;         Ti_poly and Al_mesh images (cg. Takeda et al. 2016, SolPhys. 
;         291, p.317). The resulting k-factor is obtained with the 
;         function GET_SLCORFACT_RAW.PRO, and the leak image subtraction
;         has been already performed only for the Ti_poly SCIA images at 
;         the phase 1 (as of Feb-2022).
;
; CONTACT:
;
;       Comments, feedback, and bug reports regarding this routine may be
;       directed to this email address:
;                takeda ~at~ solar.physics.montana.edu
;
; MODIFICATION HISTORY:
; 
progver = 'v2022-Feb-22' ;--- (A.Takeda) Written. 
;                         Use mk_xrt_composite.pro as a template.
progver = 'v2022-Nov-17'        ;--- (A.Takeda) Added phase 5 treatment.
progver = 'v2023-Oct-22' ;--- (A.Takeda) Added phase 6 treatment.
progver = 'v2024-Aug-27' ;--- (A.Takeda) Added phase 7 treatment.
;-
; =========================================================================
  progname = 'XRT_SYNLEAKSUB'

  loud=keyword_set(verbose)
  if (not keyword_set(verbose)) then quiet=1

  ; Added this bit so that inputs are not overwritten.
  in_idx1 = in_idx
  in_da1  = in_da
;
;  info=get_info(in_idx,/nonint)
  info=anytim(in_idx.date_obs,/ecs)+'   '+ $
      in_idx.EC_FW1_+'/'+in_idx.EC_FW2_+'   '+ $
      strtrim(string(in_idx.naxis1),2)+'x'+strtrim(string(in_idx.naxis2),2)
  if loud then print,info 

;********* check input index for leak sub history *********

chk_str='Light leak subtraction: DONE'
lsub_line=get_history(in_idx,chk_str,found=lsub_found)
if lsub_found then begin
   print,'**** input data has history of '+chk_str
   goto, FIN
endif

;********* select leak image from the archive *********
  if keyword_set(leak_image) then leak_img=leak_image $
                             else begin
;
     dir_leak='$SSW/hinode/xrt/idl/util/leak_fits/'
     filt1=in_idx.EC_FW1
     filt2=in_idx.EC_FW2
     fpair=strtrim(string(filt1),2)+strtrim(string(filt2),2)
     sl_phase=check_sl_phase(in_idx)
     leak_fn=''
;
     if fpair eq '01' then begin ;  'open/Al_mesh'
       case sl_phase of
       2: leak_fn='term_p2am_20150718_160913.fits'
       3: leak_fn='term_p3am_20170808_180126.fits'
       4: leak_fn='term_p4am_20180712_171919.fits'
       5: leak_fn='term_p5am_20220709_180901.fits'
       6: leak_fn='term_p6am_20230506_193649.fits'
       7: leak_fn='term_p7am_20240523_181532.fits'
       else: print,'No leak image available for the phase '+sl_phase   
       endcase
     endif
;
     if fpair eq '10' then begin ;  'Al_poly/open'
       case sl_phase of
       2: leak_fn='term_p2ap_20150620_172818.fits'
       3: leak_fn='term_p3ap_20170809_183821.fits'
       4: leak_fn='term_p4ap_20180712_171928.fits'
       5: leak_fn='term_p5ap_20220709_180910.fits'
       6: leak_fn='term_p6ap_20230506_193658.fits'
       7: leak_fn='term_p7ap_20240523_181541.fits'
       else: print,'No leak image available for the phase '+sl_phase   
       endcase
     endif
;
     if fpair eq '20' then begin ;  'C_poly/open'
       case sl_phase of
       2: leak_fn='term_p2cp_20150620_190645.fits'
       else: print,'No leak image available for the phase '+sl_phase   
       endcase
     endif
;
     if fpair eq '02' then begin ;  'open/Ti_poly'
       print,'Stray light component has already been subtracted '+ $
             'from the Open/Ti_poly synoptic composite images.'
;       case sl_phase of
;       1: leak_fn='term_p1tp_20140515_182503.fits'
;       2: leak_fn='term_p2tp_20150718_160921'fits'
;       else: print,'No leak image available for the phase '+sl_phase   
;       endcase
     endif
;
     if (fpair ne '01') and (fpair ne '10') and (fpair ne '20') and $
        (fpair ne '02') then begin
          print,'No leak image available for this filter pair.'
          print, info
     endif
;
     if loud then help,dir_leak,leak_fn

     if leak_fn ne '' then $
          read_xrt,dir_leak+leak_fn,leak_ind,leak_image $
     else begin
          out_idx=in_idx
          out_da=out_da
          print,'Output data are identical with the input. Returning ...'
          goto, FIN
     endelse

  endelse

;********* leak subtraction *********

  if keyword_set(kfact) then k_fact=kfact else k_fact=1.0
;
; leak sub was already done for Ti_poly at phase 1 but just in case ...
;   if fpair eq '02' and sl_phase eq 1 then $
;                    k_fact=get_slcorfact_raw(in_idx)

  leak_img2 = leak_image * k_fact 
  if in_idx.naxis1 eq 2048 then $
            leak_img2 = rebin(leak_image,2048,2048) * 0.25 * k_fact
  if loud then help,leak_img2

  out_da = in_da - leak_img2

  hist_entry1='Light leak subtraction: DONE '+ $
              'with '+leak_fn+' and kfactor:'+strtrim(string(k_fact),2)
  out_idx=in_idx
  update_history, out_idx, hist_entry1, /noroutine, /mode
;
  if loud then print,'appended to the history : '+hist_entry1
;
FIN:
if keyword_set(qstop) then stop
;
end
