;==============================================================================
;+
; Name: xsm_fits2spectrum
;
; Category: XSM, UTIL, FITS
;
; Purpose: Read spectral rate data from a FITS file, including the ENEBAND
; extension, if any.  This procedure is based on fits2spectrum.
;
; Calling sequence:
;
; Inputs:
; file - FITS file to read.
; Extnumber - extension number to find Rate
;
; Outputs:
;
; Input keywords:
; EXTNAME - keyword passed to rd_fits_ext.  Trapped.
;  The next three keywords control which extension(s) are read.  If
;  none of these are set, then all three of the primary, rate, and
;  eneband data extensions are read.
; READ_PRIMARY - Set to read primary header.
; READ_RATE - Set to read rate extension data.
; READ_ENEBAND - set to read eneband extension data.
; EXTNO - extension number to read.  Trapped.
; SETNO - number of extension with given extension type to read in
;         file.  Set this to 1 if you want the second rate extension
;         and its corresponding eneband extension.
; SILENT - Set this to suppress printing of error messages.
;
; Output keywords:
; PRIMARY_HEADER - primary FITS header
; EXT_HEADER - header for the RATE extension, with any necessary
;          keywords.
; EXT_DATA - data from the RATE / Flux extension.
; EXT_STATUS - status from mrdfits call to read rate extension.
; ENEBAND_HEADER - header from the ENEBAND extension, if any.
; ENEBAND_DATA - data from the ENEBAND extension, if any.
; ENEBAND_STATUS - status from mrdfits call to read eneband extension.
; RESPFILE - name of response file with rmf,  0 if not set in header
; ERR_MSG - error message.  Null if no error occurred.
; ERR_CODE - 0/1 if [ no error / an error ] occurred during execution.
;
; Calls:
; headfits, rd_fits_ext, ssw_pickfile
;
; Written: Sandhia Bansal - 18-Nov-2004
;          23-jun-2005, richard.schwartz@gsfc.nasa.gov - response file
;     is read from the header of the datafile.  It's no longer based on parsing
;     the data file name.
;     13-Aug-2009, Kim. Set respfile (f) to '' by default so it's defined.
;
; Modification History:
;-
;------------------------------------------------------------------------------
PRO xsm_fits2spectrum, FILE=file, $
                   EXTNAME=extname, $
                   READ_PRIMARY=read_primary, $
                   READ_RATE=read_rate, $
                   READ_ENEBAND=read_eneband, $
                   SETNO=setno, $
                   EXTNO=extno, $
                   PRIMARY_HEADER=primary_header,$
                   EXT_HEADER=ext_header, $
                   EXT_DATA=ext_data, $
                   EXT_STATUS=ext_status, $
                   ENEBAND_HEADER=eneband_header, $
                   ENEBAND_DATA=eneband_data, $
                   ENEBAND_STATUS=enband_status, $
                   RESPFILE = respfile, $

                   ERR_MSG=err_msg, $
                   ERR_CODE=err_code, $
                   SILENT=silent, $
                   _EXTRA=_extra

err_msg = ''
err_code = 1

loud = 1 - Keyword_Set( silent )

CATCH, err
IF err NE 0 THEN BEGIN
    err_msg = !err_string
    IF loud THEN MESSAGE, err_msg, /CONTINUE
    RETURN
ENDIF

read_primary = Keyword_Set( read_primary )
read_rate = Keyword_Set( read_rate )
read_eneband = Keyword_Set( read_eneband )
IF NOT( read_primary OR read_rate OR read_eneband ) THEN BEGIN
    read_primary = 1
    read_rate = 1
    read_eneband = 1
ENDIF

; if no fitsfile passed in, then popup widget dialog to select file
IF NOT keyword_set(file) THEN BEGIN
    cd, current=dir
    filename = ssw_pickfile( $
                 PATH=dir, $
                 FILTER='*.fits', $
                 TITLE='Select input file', $
                 GET_PATH=path, $
                 ERR_MSG=err_msg, $
                 ERR_CODE=err_code )
    IF filename EQ '' THEN BEGIN
        MESSAGE, err_msg, /CONTINUE
        RETURN
    ENDIF
    file = filename
ENDIF

fits_info, file, /SILENT, N_EXT=n_ext
break_file, file, disk, dir
path = disk + dir
count = 0
respfile = ''
; Check that file has extensions, and that first extension has ...TYPE...RATE... in header
if n_ext gt 0 then begin
    header1 = headfits(file, exten=1, /silent)

    ; Make sure that this header belongs to a proper XSM RATE file.  If it contains a column
    ;    called "INTEGRATION_TIME" or "TIMEDEL", then continue, otherwise display an error
    ;    message and return to the caller.
    q = where (stregex (header1, 'type.*integration_time', /boolean, /fold_case), count)
    if count eq 0 then begin
       q = where (stregex (header1, 'type.*timedel', /boolean, /fold_case), count)
       if count eq 0 then begin
        err_msg = 'Aborting.  File is not a spectrum file - ' + file
          return
       endif
    endif

    ; Get the name of the response file from the spectral file.
;    break_file, file, disk, dir, fname
;    s = strmid(fname, 3, strlen(fname))
;    respfile = $
;       concat_dir(concat_dir(disk, dir), ('TEST_'+strmid(s,0,6)+strmid(s,8,2)+'.RMF'))
    respfile = fxpar(header1, 'respfile')

    if keyword_set(respfile) then f = loc_file(path=path, respfile, COUNT=count, LOC=loc) else f=''
    IF (f EQ '') THEN BEGIN
       err_msg = ['FILE ' + files[0]+':', $
                   'has RESPFILE: ' + respfile, $
                   'RESPFILE: ' + respfile + ' not found.' ]
       err_code = 1
       RETURN
    ENDIF else respfile = f
endif


err_code = 0

IF read_primary THEN BEGIN
    primary_header = headfits( file, ERRMSG=err_msg, SILENT=silent )
    IF err_msg NE '' THEN err_code = 1
    IF err_code THEN RETURN
ENDIF

IF read_rate THEN BEGIN
    xsm_rd_fits_ext, FILE=file, $
                 EXTNUMREAD=1, $   ; First extension is RATE extension
                 SETNUMBER=setno, $
                 HEADER=ext_header, $
                 DATA=ext_data, $
                 STATUS=ext_status, $
                 ERR_MSG=err_msg, $
                 ERR_CODE=err_code, $
                 SILENT=silent
    IF err_code THEN RETURN
ENDIF

IF read_eneband THEN BEGIN
    xsm_rd_fits_ext, FILE=respfile, $
                 EXTNAME='EBOUNDS', $
                 SETNUMBER=setno, $
                 HEADER=eneband_header, $
                 DATA=eneband_data, $
                 STATUS=enband_status, $
                 ERR_MSG=err_msg, $
                 ERR_CODE=err_code, $
                 SILENT=silent
ENDIF

END

