;+
;
; NAME:
;   spex_xsm_fits2drm
;
; PURPOSE:
;   Read FITS formatted XSM response matrix File (RMF) and Ancilliary Response File (ARF),
;   multiply the two to create the Detector Response Matrix (DRM) and return information of
;   interest to OSpex.
;   NOTE: This procedure is based on spex_hessi_fits2drm.
;
;
; CATEGORY:
;       SPECTRAL FITTING, SPEX - XSM
;
; CALLING SEQUENCE:
;
; CALLS:
;   fits2rm, fxpar
;
; INPUTS:
;
; OUTPUTS:
;
; INPUT KEYWORDS:
;   RMFFILE - name of FITS file to read (contains RMF).
;
;   SFILE - not used.  Included for Spex comptability.
;
; OUTPUT KEYWORDS:
;     drm_str - structure with drm info
;
; PROCEDURE:
;
; Written 23-Nov-2004  - Sandhia Bansal
;
; Modification History:
; 12/08/04 - Sandhia Bansal - Modified a comment.
;   23-jun-2005, richard.schwartz@gsfc.nasa.gov - removed ancrfile from arg list
;     ancrfile name given by rmffile header and these two
;   are combined based on the number of channels in the files, does not assume 512
;   24-jun-2005, ras, corrected drm normalization, removed division by photon bin width
;   27-jun-2005, ras, normalized arf by nominal geometric area
;	13-May-2008, Kim. Added drm_obj keyword and remove ct_energies < data's ct_energies from drm array
;	  and drm ct_energies, and ph energies < 1 keV.
;	25-Jun-2015, Kim. Some files (e.g. 31-jul-2004 from shyama) had excess energy bins all set to [20.,20.] keV.
;	  These extra bins caused a crash, so now remove bins > data energy bins (see corresponding change in read_xsm_4_ospex)
;-
;------------------------------------------------------------------------------
PRO spex_xsm_fits2drm, FILE=rmffile, $

                       SFILE=sfile, $
                       drm_obj=drm_obj, $
                       drm_str, $
                       ERR_CODE=err_code, $
                       ERR_MSG=err_MSG

drm_str = -1

; Read RMF
fits2rm, rmffile[0], $
         RM=drm, $
         EBINS=ph_edges, $
         DETBINS=edges_out, $
         EXT_HEADER=hdr, $
         ERR_CODE=err_code, $
         ERR_MSG=err_msg

IF err_code THEN RETURN

data_name = get_fits_instr(hdr)



; Read ARF from the SPECRESP extension of the ARF(ancrfile) file.
ancrfile = fxpar( hdr,'ancrfile', count=count)
break_file, rmffile[0], disk, dir
path = concat_dir( disk, dir, /dir)
if count eq 1 then ancrfile = loc_file(path=path, ancrfile,count=count)

if count eq 0 then begin
    err_msg = 'ANCRfile not found or not specified'
    err_code = 1
    return
    endif


o = fitsread( filename = ancrfile );

arf = o-> getfield( extension =  1,  'SPECRESP' )
hdr = o->getheader()
area = fxpar( hdr, 'GEOAREA', COUNT=count )
area = count GT 0L ? st2num( area ) : 1.


arf = arf[*,0]   ; get the first row - assume for now that we have a time-independent
                 ;    ARF which can be applied to all spectra contained in the PHAII file.

;
; Divide each row by detector channel width as expected by reader
dcte = get_edges(edges_out, /width)
dphe = get_edges(ph_edges, /width)
narf = n_elements(arf)
for i=0,narf-1 do $
drm[0,i] = drm[*,i] * arf[i]/dcte/area[0]

atten_state = -1
sepdets = 0
detused = ''

; don't keep any ct energies below lowest energy in data (they don't match
; because we eliminated energies < 1keV in xsm reader),  and don't keep any
; ph energies < 1 keV (these changes are because of restrictions in chianti)
data_en = (drm_obj->get(/spex_drm_dataobj)) -> get(/spex_ct_edges)
;q = where (edges_out[0,*] ge data_en[0,0])
;ec = q[0]
;q = where (ph_edges[0,*] gt 1.)
;ep = q[0]
;edges_out = edges_out[*,ec:*]
;ph_edges = ph_edges[*,ep:*]
;drm = drm[ec:*,ep:*]

; Eliminate energies < 1 keV and also greater than the max of the data energies (note change in read_xsm_4_ospex)
qc = where (edges_out[0,*] ge data_en[0,0] and edges_out[0,*] le max(data_en))
qp = where (ph_edges[0,*] gt 1.)
edges_out = edges_out[*,qc]
ph_edges = ph_edges[*,qp]
drm = drm[*,qp] ; can't do [qc,qp] in one step
drm = drm[qc,*]

drm_str = { $
    EDGES_OUT: edges_out, $
    PH_EDGES: ph_edges, $
    AREA: area, $
    DRM: drm, $
    SEPDETS: sepdets, $
    data_name: data_name, $
    filter: atten_state, $
    detused: detused }

END

