function IRIS_PREP_GET_BACK, index, version

;+
; NAME:
;       iris_prep_get_back()
;
; PURPOSE:
;       A function to estimate the FUV spectrograph stray light
;       background image.  A normalized background image is loaded and
;       scaled based on the telescope pointing, exposure time, and
;       binning.  The pointing-dependent background count rate is
;       estimated using a smoothed limb darkening function for a
;       wavelength of 500 nm.  The parameters for this function were
;       determined empirically for each filter (filter back-reflection
;       of visible-IR light onto slit prism seems to be the culprit). 
;
;       Some remaining questions:
;          Do level 1 data coordinates need to be updated?
;          Which index variable contains the proper roll angle?  
;          Do I have the sign right on roll angle?
;
; CALLING SEQUENCE:
;       image = iris_prep_get_back(index)
;
; INPUTS:
;       index - An IRIS FUV spectrograph image index structure for
;               level 1 or 1.5 data.
;
; OPTIONAL INPUTS:
;
; KEYWORD PARAMETERS:
;
; OUTPUTS:
;       Returns an array containing the estimate of the stray light image. 
;
; OPTIONAL OUTPUTS:
;       version	-	A string giving the YYYYMMDD of the data used
;				(gets saved in the header as a LONG, but that's ok)
;
; COMMON BLOCKS:
;       IRIS_PREP_BACK_CB, bg_img, bg_head, ver_string, all_ver_strings
;
; PROCEDURES USED:
;       iris_back_func - function for calculating the smoothed limb
;                        darkening function
;
; COMMENTS:
;       Function must be given one index at a time, images should be
;       dark subtracted, but not yet flat fielded.
;
; EXAMPLES:
;          IDL> image = iris_get_back(index)
;
; MODIFICATION HISTORY:
;       Started 2013-Nov-14 by Sarah A. Jaeggli, Montana State University
;		Minor SSW tweaks 2013-Dec-03 by P. Boerner, LMSAL
;		Moved from iris_get_back to iris_prep_get_back 2013-Dec-13 PB
;       2022-08-10 RPT changing calibration files location  
;
;-

common IRIS_PREP_BACK_CB, bg_img, bg_head, ver_string, all_ver_strings, all_ver_tai

; Check if index is a structure
if N_TAGS(index) eq 0 then begin
	print, 'This is not a header structure, exiting...'
	return, 0
endif

;check if image is FUV
if index.img_path ne 'FUV' then begin
	print, 'This is not FUV data, exiting...'
	return, 0
endif

; Calibration data directory
sswdata = CONCAT_DIR('$SSWDB','iris/data')

;relevant properties of the data which need to be read from the index are:
;pointing, roll angle
xcen0 = index.xcen
ycen0 = index.ycen
roll  = index.sat_rot ;roll angle from solar north
rsun  = index.rsun_obs

;rotate coordinates so they are w.r.t roll
xcen = xcen0*cos(roll/180.*!pi) - ycen0*sin(roll/180.*!pi)
ycen = xcen0*sin(roll/180.*!pi) + ycen0*cos(roll/180.*!pi)

;filter
fw = index.ifwpos

;exposure time
exp=index.exptime

;binning
ybin=float(index.sumspat)
xbin=float(index.sumsptrl)

; absolute time of observation
taiobs= ANYTIM2TAI(index.t_obs)

; Check to see if the common block is populated; if not, load the list of
; available background files
if N_ELEMENTS(all_ver_strings) eq 0 then begin
	backfiles = FILE_SEARCH(CONCAT_DIR(sswdata, '*FUV_background.fits'))
	if backfiles[0] eq '' then begin
		PRINT, 'IRIS_PREP_GET_BACK: No background file found!'
		RETURN, FLTARR(nx/xbin, ny/ybin)
	endif
	all_ver_strings = STRMID(FILE_BASENAME(backfiles), 0, 15)
	all_ver_tai = ANYTIM2TAI(FILE2TIME(all_ver_strings))
	ver_string = '00000000_000000'
endif

; Check to see whether the proper background image is loaded; if not, load it
taidiff = ABS(taiobs - all_ver_tai)
index_addr = WHERE(taidiff eq MIN(taidiff))
use_ver = all_ver_strings[index_addr]
if ver_string ne use_ver then begin
	bg_file = CONCAT_DIR(sswdata, use_ver + '_FUV_background.fits')
	MREADFITS, bg_file, bg_head, bg_img
	ver_string = use_ver
endif

version = ver_string
nx = (size(bg_img))[1]
ny = (size(bg_img))[2]

; Load limb-darkening parameters depending on the SJ filter position
case fw of
     ;ld_pars =  x0[arcsec], y0[arcsec], gaussian width[arcsec], 
     ;             amplitude[DN/sec], offset[DN/sec]

     ;1330
     31  : ld_pars = [bg_head.ld31_0, bg_head.ld31_1, bg_head.ld31_2, bg_head.ld31_3, bg_head.ld31_4]

     ;2796
     61  : ld_pars = [bg_head.ld61_0, bg_head.ld61_1, bg_head.ld61_2, bg_head.ld61_3, bg_head.ld61_4]

     ;1400
     91  : ld_pars = [bg_head.ld91_0, bg_head.ld91_1, bg_head.ld91_2, bg_head.ld91_3, bg_head.ld91_4]

     ;2832
     121 : ld_pars = [bg_head.ld121_0, bg_head.ld121_1, bg_head.ld121_2, bg_head.ld121_3, bg_head.ld121_4]

     ;5000
     1   : begin
        print, 'No data available for the 5000A filter, exiting...'
        return, 0
     end

     ;1600
     151 : begin
        print, 'No data available for the 1600A filter, exiting...'
        return, 0
     end

	 ;Other     
     else	:	begin
     	print, 'Funny FW position, exiting...'
     	return, 0
     end
     
endcase

;calculate smoothed limb darkening function
bg_level = iris_back_func(xcen, ycen, [ld_pars, rsun])

;scale intensity
back = bg_img*bg_level*exp

;account for binning
back = rebin(back, nx/xbin, ny/ybin, /SAMPLE)*xbin*ybin

return, back

end
