pro euvi_prep,hdr,im,fill_mean=fill_mean,fill_value=fill_value,smask_on=smask_on,calibrate_off=calibrate_off, rotate_on=rotate_on,ROTINTERP_ON=ROTINTERP_ON,rotcubic_on=rotcubic_on,color_on=color_on,date_on=date_on,logo_on=logo_on,silent=silent,update_hdr_off=update_hdr_off,POINTING_OFF=pointing_off,dejitter_on=dejitter_on, _extra=ex

;+
;$Id: euvi_prep.pro,v 1.33 2023/08/15 22:17:14 secchia Exp $
;
; Project   : STEREO SECCHI
;
; Name      : euvi_prep
;
; Purpose   : Processes a STEREO Extreme UltraViolet Imager (EUVI) image
;             to level 1.0
;
; Explanation: The default correction procedure involves; subtracting
;        the CCD bias, multiplying by the correction factor, normalize
;        to OPEN filter position and vignetting function, and dividing 
;        by the exposure time. Any of these operations
;        can turned off using the keywords. 
;               
; Use      : IDL> cor_prep,hdr,im
;
; Inputs   : im - level 0.5 image in DN (long)
;            hdr -image header, either fits or SECCHI structure
;
; Outputs   :  
;
; Keywords  : SMASK_ON - applied a smooth mask to the image, if set
;                        then tele_only is also set
;             FILL_MEAN - if set then missing data and the mask are
;                         set to the mean of the images; the default
;                         is zero
;             FILL_VAULE -    if set then missing data and the mask are
;                         set to the input value; the default
;                         is zero        
;             CALIBRATE_OFF - if set no photometeric calibration is
;                             applied; this keyword set if the
;                             trim_off keyword was set in SECCHI_PREP
;             ROTATE_ON - rotates the image such that solar north is at
;                      the top of the image
;             ROTINTERP_ON - Use bilinear interpolation for the
;                            rotation (if ROTATE_ON is set). Default
;                            is nearest neighbor.
;             ROTCUBIC_ON - Use cubic convolution interpolation method
;                           for the rotation (if ROTATE_ON is set). Default
;                            is nearest neighbor.
;             DEJITTER_ON - Adjusts the image position to correct for
;                           spacecraft jitter.  It is recommended that this be
;                           done in conjunction with /ROTATE_ON.  The keywords
;                           /ROTINTERP_ON and /ROTCUBIC_ON also apply to
;                           /DEJITTER_ON.
;             DATE_ON - Adds date-time stamp to bottom left of image
;             LOGO_ON - Adds SECCHI logo to bottom right of image
;             COLOR_ON - loads instrument color table
;             UPDATE_HDR_OFF- if set, don't call SCC_UPDATE_HDR (saves time)
;   	      POINTING_OFF - Do not correct CRPIX in header with euvi_point.pro  
;
; Common    : 
;
; Calls     : SCC_FITSHDR2STRUCT, SCC_GET_MISSING, EUVI_CORRECTION, 
;             SCC_UPDATE_HDR, SCC_ADD_DATETIME, SCC_ADD_LOGO
;               
; Category    : Calibration
;               
; Prev. Hist. : None.
;
; Written     : Robin C Colaninno NRL/GMU August 2006
;
;Revision 1.21  2007/04/04 15:27:26  colaninn
;reversed output parameters
;
;Revision 1.20  2007/04/03 15:56:18  thernis
;Add /pivot in the rot statement
;
;Revision 1.19  2007/04/02 14:11:47  colaninn
;removed update 1.15
;
;Revision 1.18  2007/03/30 22:14:02  thompson
;*** empty log message ***
;
;Revision 1.17  2007/03/30 22:12:54  thompson
;Add keyword update_hdr_off
;
;Revision 1.16  2007/03/30 20:30:29  colaninn
;add keyword to rot
;
;Revision 1.15  2007/03/27 13:56:42  colaninn
;add crval to rotate
;
;Revision 1.14  2007/02/26 19:11:54  colaninn
;removed mask keyword calls
;
;Revision 1.13  2007/02/13 15:59:55  thernis
;Add ROTINTERP_ON keyword to allow bilinear interpolation when using the ROTATE_ON keyword
;
;Revision 1.12  2007/02/06 21:28:39  colaninn
;corrected header
;
;Revision 1.11  2007/02/06 21:25:13  colaninn
;add if for header update
;
;Revision 1.10  2007/01/22 19:47:17  colaninn
;add correct color file path
;
;Revision 1.9  2007/01/19 17:15:19  colaninn
;added data and logo stamp
;
;Revision 1.8  2007/01/17 15:31:30  colaninn
;added color table loading
;
;Revision 1.7  2006/12/14 21:32:36  colaninn
;added rotate_on keyword
;
;Revision 1.6  2006/12/12 20:52:39  colaninn
;added rotate keyword
;
;Revision 1.5  2006/12/07 21:16:53  colaninn
;added get_smask
;
;Revision 1.4  2006/11/27 19:54:49  colaninn
;cor/cor_calibrate.pro
;
;Revision 1.3  2006/11/21 22:12:54  colaninn
;Made corrections for Beta 2
;
;Revision 1.2  2006/10/24 20:42:22  colaninn
;added calibrate_off keyword
;
;Revision 1.1  2006/10/03 15:30:16  nathan
;moved from dev/analysis/euvi
; 
;-
ON_ERROR,2
IF datatype(ex) EQ 'UND' THEN ex = create_struct('blank',-1)
IF keyword_set(silent) THEN ex = create_struct('silent',1,ex)

IF ~keyword_set(silent) THEN print,'$Id: euvi_prep.pro,v 1.33 2023/08/15 22:17:14 secchia Exp $'

;--Check Header-------------------------------------------------------
IF(datatype(hdr) NE 'STC') THEN hdr=SCC_FITSHDR2STRUCT(hdr)

IF ~strmatch(TAG_NAMES(hdr,/STRUCTURE_NAME),'SECCHI_HDR_STRUCT*') THEN $
MESSAGE, 'ONLY SECCHI HEADER STRUCTURE ALLOWED'

IF (hdr[0].DETECTOR NE 'EUVI') THEN $
 message,'Calibration for EUVI DETECTOR only'
;----------------------------------------------------------------------

;--Check Keywords
IF datatype(ex) EQ 'UND' THEN ex = create_struct('blank',-1)

;--Pointing (Sun-center) Correction (ON)
IF ~keyword_set(POINTING_OFF) THEN $
    euvi_point, hdr, QUIET=silent, _EXTRA=ex
    
;--Cosmic Ray Removal(OFF)
IF KEYWORD_SET(cosmic_on) THEN BEGIN
;  image = cosmicr(image) ;CALL EIT_DARK not EUVI COMPATIBLE
endif
 
;--Missing Blocks (ON)
IF(hdr[0].MISSLIST NE '') AND ~keyword_set(calibrate_off) THEN BEGIN
   missing = SCC_GET_MISSING(hdr)
ENDIF

;--Correction DN to detected photons(ON)
IF ~keyword_set(calibrate_off) THEN BEGIN
  im = EUVI_CORRECTION(im,hdr,_extra=ex)
ENDIF

;--Missing Block Mask(ON) or SURROUND(OFF) FILL(OFF)
IF (hdr[0].MISSLIST NE '') AND ~keyword_set(calibrate_off) THEN BEGIN 
  CASE 1 OF
    keyword_set(fill_mean) : missval=mean(im) 
    keyword_set(fill_value) : missval=fill_value
    ELSE: missval=0.0
  ENDCASE
  hdr.blank=missval
  im[missing]=missval
  IF ~keyword_set(SILENT) THEN message,'Missing blocks filled with ' +trim(missval), /info
ENDIF ELSE missing = 0

;--Warp(ON)
   ;Geometric distortion no warp function exists

;--Dejitter (OFF)
offset = [0., 0.]
if keyword_set(dejitter_on) then begin
    nsum = 2.^(hdr.summed-1)
    offset[0] = round(hdr.fpsoffz/38.) / nsum
    offset[1] = round(hdr.fpsoffy/38.) / nsum
    if hdr.obsrvtry eq 'STEREO_B'   then offset = -offset
    if (hdr.date_obs lt '2015-05-19') or (hdr.date_obs ge '2023-08-12') then $
      offset = -offset
;
;  If ROTATE_ON is set, then defer the interpolation to SCC_ROLL_IMAGE.
;
    if ((offset[0] ne 0) or (offset[1] ne 0)) and $
      ~keyword_set(rotate_on) then begin
        cx = [-offset[0], 0, 1, 0]
        cy = [-offset[1], 1, 0, 0]
        itype = keyword_set(rotinterp_on)
        im = poly_2d(im, cx, cy, itype, MISSING=0, $
                     cubic=keyword_set(rotcubic_on))
        hdr.crpix1 = hdr.crpix1 + offset[0]
        hdr.crpix2 = hdr.crpix2 + offset[1]
        hdr.crpix1a = hdr.crpix1a + offset[0]
        hdr.crpix2a = hdr.crpix2a + offset[1]
        hdr.xcen = hdr.xcen - hdr.cdelt1 * offset[0]
        hdr.ycen = hdr.ycen - hdr.cdelt2 * offset[1]
    endif
endif

;--Rotate Solar North Up (OFF)
IF keyword_set(rotate_on) THEN BEGIN
    scc_roll_image,hdr,im, missing=0, interp=keyword_set(rotinterp_on), $
    	    cubic=keyword_set(rotcubic_on), offset=offset, _extra=ex
    
    IF ~keyword_set(SILENT) THEN message,'Image rotated to Solar North Up',/info
ENDIF

;--Smooth Mask(OFF)
IF keyword_set(smask_on) AND ~keyword_set(calibrate_off) THEN BEGIN 
  mask = get_smask(hdr)
  m_dex = where(mask EQ 0)
    CASE 1 OF
      keyword_set(fill_mean) : im[m_dex]=mean(im) 
      keyword_set(fill_value) : im[m_dex]=fill_value
      ELSE: im = im*mask
    ENDCASE 
    IF ~keyword_set(SILENT) THEN message,'Mask applied',/info
ENDIF

;--Telescope Color Table   
IF keyword_set(color_on) THEN BEGIN    
  path = concat_dir(getenv('SSW'),'stereo')
  color_table = strtrim(string(hdr.WAVELNTH),2)+'_EUVI_color.dat'
  RESTORE, FILEPATH(color_table ,ROOT_DIR=path,$
            SUBDIRECTORY=['secchi','data','color'])
  tvlct, r,g,b
ENDIF

;--Update Header to Level 1 values (ON)
IF ~keyword_set(calibrate_off) AND ~keyword_set(update_hdr_off) THEN $
  hdr = SCC_UPDATE_HDR(im,hdr,missing=missing,_extra=ex)

;--Date and Logo Stamp (OFF)
IF keyword_set(date_on) THEN im = SCC_ADD_DATETIME(im,hdr)

IF keyword_set(logo_on) THEN im = SCC_ADD_LOGO(im,hdr)


;-----------------------------------------------------------------------------
RETURN
END

