FUNCTION make_xrt_ea, input1, channels, intype=intype,         $
                      contam=contam_out, fcontam=fcontam_out,          $
                      verbose=verbose, quiet=quiet, qabort=qabort, qstop=qstop

; =========================================================================
;+
; PROJECT:
;       Solar-B / XRT 
;
; NAME:
;       
;       MAKE_XRT_EA
;
; CATEGORY:
;       
;       Instrument response
;
; PURPOSE:
;
;       Produce the effective areas for a set of XRT x-ray channels
;       paired with thicknesses of the CCD contamination layer.
;       (This subroutine of <make_xrt_wave_resp.pro> replaces 
;       <calc_xrt_effarea.pro>.)
;
; CALLING SEQUENCE:
;
;       Result = MAKE_XRT_EA( input1, channels [,intype=intype]
;                  [,contam=contam] [,fcontam=fcontam] [,/verbose] [,/quiet] 
;                  [,qabort=qabort] [,/qstop]                )
;
; INPUTS:
;
;       INPUT1      - [Mandatory] index structure array, (default);
;                              OR pair of thicknesses [CCD,filter1+2];
;                                               (two element float array);
;                              OR time of observation  (string)
;                     To calculate the contamination transmission, a pair of
;                     layer thicknesses must be provided (in Angstroms).
;                     The default mode is to assume that INPUT1 is an
;                     index structure, from which the filter and time
;                     information to calculate thickensses can be extracted.   
;                     Alternately, a pair of layer thicknesses [CCD,filter1+2]
;                     or a time may be provided.  Times must be 
;                     provided in a string format that SSWIDL will recognize.
;                     If thicknesses or times are provided, INTYPE must
;                     be set to 1 or 2 respectively (see INTYPE below).
;       CHANNELS    - [Mandatory] (structure array, 
;                                  {XRT_chn_config_vNNNN} [Nthicknesses])
;                     This is an array of structures of type
;                     "XRT_chn_config" and with a structure name
;                     of the form {XRT_chn_config_vNNNN}. For a
;                     more complete description of this complicated
;                     structure, see the XRT Analysis Guide. The
;                     base set of channels is provided in the XRT SSWIDL 
;                     tree by a file with a pathname like this:
;       $SSW_XRT/idl/response/channels/xrt_channels_vNNNN.geny
;                     That file is automatically found, read, and passed 
;                     to <make_xrt_ea.pro> if <make_xrt_wave_resp.pro> 
;                     is used as the interface, as intended.
;
; KEYWORDS:
;
;        INTYPE - [Optional] (integer scalar) This keyword is set to:
;                  = 0: INPUT1 is an index structure (Default)
;                  = 1: INPUT1 is a 2xN vector of paired thicknesses
;                       [CCD, filter1+2] (in Angstroms).
;                  = 2: INPUT1 is a list of times of XRT images
;                       (<anytim2utc.pro> format).
;                  [Mandatory] if input is thicknesses or image times.
;       /VERBOSE    - [Optional] (Boolean) If set, print out extra
;                     information. Overrides "/quiet" (see Note #1).
;       /QUIET      - [Optional] (Boolean) If set, suppress messages
;                     (see Note #1).
;       /QSTOP      - [Optional] (Boolean) For debugging.
;
;
; OUTPUTS:
;
;       Return      - [Mandatory] (structure array,
;       (EFF_AREAS)   {XRT_eff_area_vNNNN} [Nchannels])
;                     This structure array contains data and
;                     information about the effective areas for a
;                     set of x-ray channels paired with contamination
;                     layer thicknesses. 
;
;                     EFF_AREAS {XRT_eff_area_vNNNN}
;                     - TYPE            (string scalar)
;                     - EFF_STR_VERSION (string scalar)
;                     - EFF_STR_DESCR   (string scalar)
;                     - NAME            (string scalar)
;                     - WAVE            (float array, [Nwave])
;                     - WAVE_UNITS      (string scalar)
;                     - EFF_AREA        (float array, [Nwave])
;                     - EFF_AREA_UNITS  (string scalar)
;                     - LENGTH          (long scalar)
;                     - HISTORY         (string array, [3])
;                     - COMMENTS        (string array, [5])
;
;                     Here are descriptions of the fields in the
;                     "XRT_eff_area" structure.:
;
;                     TYPE: (string scalar)
;                         [Default value = 'XRT_eff_area'.]
;                         This is the generic name of the structure
;                         that contains the effective areas and
;                         related information. The version of the
;                         structure definition might evolve, but
;                         the TYPE should remain constant. See
;                         EFF_STR_VERSION. This field should NOT
;                         be changed.
;                     EFF_STR_VERSION: (string scalar)
;                         [The default value = 'XRT_eff_area_vNNNN',
;                         where NNNN is a 4-digit number.]
;                         This is the version number of the "XRT_eff_area"
;                         structure definition. In addition to being
;                         recorded in this field, this is also the
;                         "unique structure name" in the IDL sense.
;                         This field should NOT be changed.
;                     EFF_STR_DESCR: (string scalar)
;                         This is a sentence or two that describes the
;                         purpose of this structure type. This field
;                         should NOT be changed.
;                     NAME: (string scalar)
;                         This is a name for this pair of XRT x-ray
;                         channel and contamination layer thickness.
;                         This string should be a concise identifier
;                         (although it may not be unique). Some
;                         programs may refer to this string, so its
;                         usage should be regularized. This field
;                         MAY be changed, but the default is
;                         recommended.
;                     WAVE: (float array, [Nwave])
;                         The wavelength abscissa of the effective
;                         area function (see EFF_AREA tag) for a
;                         specified pair of XRT x-ray channel and
;                         contamination layer thickness. The values
;                         must make a montonically increasing
;                         sequence of floating point numbers,
;                         starting from the first address of the
;                         array. If the sequence is shorter than
;                         the length of this array, then all addresses
;                         after the sequence ends should have a
;                         value of zero. The sequence length is
;                         recorded in the LENGTH tag. The values
;                         must be consistent with the units named
;                         in WAVE_UNITS.
;                     WAVE_UNITS: (string scalar)
;                         Units of the value in the WAVE tag. The units
;                         must be 'Angstroms' (so that other programs
;                         can reliably interpret WAVE).
;                     EFF_AREA: (float array, [Nwave])
;                         The x-ray channel's effective area as a
;                         function of wavelength (see WAVE), with
;                         accounting for some thickness of the CCD
;                         contamination layer. The values must
;                         make a sequence of floating point numbers,
;                         starting from the first address of the
;                         array, and should correspond in position
;                         to values of WAVE. If the sequence is
;                         shorter than the length of this array,
;                         then all addresses after the sequence
;                         ends should have a value of zero. The
;                         sequence length is recorded in the LENGTH
;                         tag. The values must be consistent with
;                         the units named in EFF_AREA_UNITS.
;                     EFF_AREA_UNITS: (string scalar)
;                         Units of the value in the EFF_AREA tag.
;                         The units must be 'cm^2' (so that other
;                         programs can reliably interpret EFF_AREA).
;                     LENGTH: (long scalar)
;                         The length of the paired sequences of WAVE
;                         and EFF_AREA, indicating how much of those
;                         arrays contains useful information. E.g.:
;                         IDL> len = eff_areas[0].length
;                         IDL> plot, eff_areas[0].wave[0:len-1],  $
;                         IDL>       eff_areas[0].eff_area[0:len-1]
;                     HISTORY: (string array, [3])
;                         This text array is for XRT programs to
;                         record any instance in which they have
;                         modified the content of the "XRT_eff_area"
;                         type of structure for this particular
;                         pair of XRT x-ray channel and contamination
;                         layer thickness.  On creation, a line is
;                         added for the creation of the "XRT_eff_area"
;                         structure in <make_xrt_ea.pro>.  An entry
;                         string is composed of (a) a program name,
;                         (b) the program's version/date, (c) colon
;                         separator, (d) Timestamp (in parentheses)
;                         of when the program completed the described
;                         action, and (e) a summation of what the
;                         program created or modified in the
;                         "XRT_eff_area" structure.  Values are
;                         inserted starting at the lowest address
;                         of this array. Remaining unused addresses
;                         are filled with the empty string.  Filled
;                         strings should NOT be overwritten.  Users
;                         should use the COMMENTS field to add their
;                         own notations to this structure.
;                     COMMENTS: (string array, [5])
;                         A tag for adding notations regarding this
;                         specific effective area.  Users and
;                         programs are encouraged to put content
;                         in the lower addresses, and assign empty
;                         strings {''} to the higher, unused
;                         addresses.
;
;       CONTAM      - [Optional] (structure array,
;                                 {XRT_contam_ref_vNNNN} [Nthicknesses])
;                     This structure contains information
;                     about the CCD contamination layer for a given
;                     thickness. The thickness varies with time between
;                     CCD bakeouts and acts like an extra filter layer,
;                     so the transmission factor must be included when
;                     calculating the effective area for each XRT
;                     channel for any given image or point in time.
;
;                     Here is a listing of the fields of the
;                     "XRT_contam_ref" structure. Descriptions are
;                     provided further down.:
;
;                     CONTAM {XRT_contam_ref_vNNNN}
;                     - TYPE            (string scalar)
;                     - CTM_STR_VERSION (string scalar)
;                     - CTM_STR_DESCR   (string scalar)
;                     - NAME            (string scalar)
;                     - LONG_NAME       (string scalar)
;                     - MATERIAL        (string scalar)
;                     - DENS            (float scalar)
;                     - DENS_UNITS      (string scalar)
;                     - THICK           (float scalar)
;                     - THICK_UNITS     (string scalar)
;                     - THICK_TIME      (string scalar)
;                     - DATA_FILES      (string array, [5])
;                     - HISTORY         (string array, [3])
;                     - COMMENTS        (string array, [5])
;
;                     Here are descriptions of the fields in the
;                     "XRT_contam_ref" structure.:
;
;                     TYPE: (string scalar)
;                         [Default value = 'XRT_contam_ref'.]
;                         This is the generic name of the structure
;                         that contains the contamination functions
;                         and information. The version of the structure
;                         definition might evolve, but the TYPE should
;                         remain constant. See CTM_STR_VERSION. The
;                         value is initialized at creation. This field
;                         should NOT be changed.
;                     CTM_STR_VERSION: (string scalar)
;                         [The default value = 'XRT_contam_ref_vNNNN',
;                         where NNNN is a 4-digit number.]
;                         This is the version number of the "XRT_contam"
;                         structure definition. In addition to being
;                         recorded in this field, this is also the
;                         "unique structure name" in the IDL sense.
;                         The value is initialized at creation. This
;                         field should NOT be changed.
;                     CTM_STR_DESCR: (string scalar)
;                         This is a sentence or two that describes the
;                         purpose of this structure type. This field
;                         should NOT be changed.
;                     NAME: (string scalar)
;                         This is a name for this contamination layer
;                         thickness. This string should concisely
;                         identify the contamination layer (although
;                         it may not be unique). Some programs may
;                         refer to this string, so its usage should
;                         be regularized. (Compare to LONG_NAME.) This
;                         field MAY be changed, but the default is
;                         recommended.
;                     LONG_NAME: (string scalar)
;                         This is a longer string for the name for
;                         this contamination layer thickness. This
;                         field should not be referred to by software;
;                         it is intended to provide a more informative
;                         description for humans.  This field MAY be
;                         changed, but the default is recommended.
;                     MATERIAL: (string scalar)
;                         Name of substance or chemical compound forming
;                         the contamination layer. (NAME may or may
;                         not specify the substance's identity. MATERIAL
;                         should always specify the substance's
;                         identity.)
;                     DENS: (float scalar)
;                         Density of the contamination material named
;                         in the MATERIAL tag, and that was used to
;                         calculate the transmission function. The
;                         value must be consistent with the units named
;                         in DENS_UNITS.
;                     DENS_UNITS: (string scalar)
;                         Units of the value in the DENS tag. The units
;                         must be 'g cm^-3' (so that other programs
;                         can reliably interpret DENS).
;                     THICK: (float scalar)
;                         Thickness of the contamination material named
;                         in the MATERIAL tag, and that was used to
;                         calculate the transmission function. The
;                         value must be consistent with the units named
;                         in THICK_UNITS.
;                     THICK_UNITS: (string scalar)
;                         Units of the value in the THICK tag. The
;                         units must be 'Angstroms' (so that other
;                         programs can reliably interpret THICK).
;                     THICK_TIME: (string scalar)
;                         This is the mission time for which the
;                         contamination thickness (tag THICK) was
;                         calculated, as specified by INPUT1 and keyword
;                         INTYPE=0. It is possible that the thickness
;                         was asserted independent of a mission time
;                         (using INPUT1 and INTYPE=2), in which case
;                         the THICK_TIME tag may have an empty string
;                         value (''). The value should be in a string
;                         time format recognized by SSWIDL.
;                     DATA_FILES: (string array, [5])
;                         This is a list of filenames of reference
;                         data that were used in the specification of
;                         the contamination. It is primarily intended
;                         for listing any files that might be important
;                         for reference purposes.  This field should
;                         NOT be changed, but empty strings may be
;                         added to.
;                     HISTORY: (string array, [3])
;                         This text array is for XRT programs to record
;                         any instance in which they have modified the
;                         content of the "XRT_contam" type of structure
;                         for this particular contamination description.
;                         On creation, a line is added for the creation
;                         of the "XRT_contam" structure in
;                         <make_xrt_contam.pro>.  An entry string is
;                         composed of (a) a program name, (b) the
;                         program's version/date, (c) colon separator,
;                         (d) Timestamp (in parentheses) of when the
;                         program completed the described action, and
;                         (e) a summation of what the program created
;                         or modified in the "XRT_contam" structure.
;                         Values are inserted starting at the lowest
;                         address of this array. Remaining unused
;                         addresses are filled with the empty string.
;                         Filled strings should NOT be overwritten.
;                         Users should use the COMMENTS field to add
;                         their own notations to this structure.
;                     COMMENTS: (string array, [5])
;                         A tag for adding notations regarding this
;                         specific contamination layer and thickness.
;                         Users and programs are encouraged to put
;                         content in the lower addresses, and assign
;                         empty strings {''} to the higher, unused
;                         addresses.
;
;       FCONTAM      - [Optional] (structure array,
;                                 {XRT_filt_contam_ref_vNNNN} [Nthicknesses])
;                     This structure contains information about the
;                     combined filter contamination layers for a given
;                     combined thickness. The thickness varies with the 
;                     amount of time a given filter is in use, and acts 
;                     like an extra absorption layer,
;                     so the transmission factor must be included when
;                     calculating the effective area for each XRT
;                     channel combination for any given image or point in time.
;
;                     Here is a listing of the fields of the
;                     "XRT_filt_contam_ref" structure. Descriptions are
;                     provided further down.:
;
;                     FCONTAM {XRT_filt_contam_ref_vNNNN}
;                     - TYPE            (string scalar)
;                     - FCTM_STR_VERSION (string scalar)
;                     - FCTM_STR_DESCR   (string scalar)
;                     - FILTER1         (string scalar)
;                     - FILTER2         (string scalar)
;                     - NAME            (string scalar)
;                     - LONG_NAME       (string scalar)
;                     - MATERIAL        (string scalar)
;                     - DENS            (float scalar)
;                     - DENS_UNITS      (string scalar)
;                     - THICK           (float scalar)
;                     - THICK_UNITS     (string scalar)
;                     - THICK_TIME      (string scalar)
;                     - DATA_FILES      (string array, [5])
;                     - HISTORY         (string array, [3])
;                     - COMMENTS        (string array, [5])
;
;                     Here are descriptions of the fields in the
;                     "XRT_contam_ref" structure.:
;
;                     TYPE: (string scalar)
;                         [Default value = 'XRT_filt_contam_ref'.]
;                         This is the generic name of the structure
;                         that contains the contamination functions
;                         and information. The version of the structure
;                         definition might evolve, but the TYPE should
;                         remain constant. See FCTM_STR_VERSION. The
;                         value is initialized at creation. This field
;                         should NOT be changed.
;                     FCTM_STR_VERSION: (string scalar)
;                         [The default value = 'XRT_filt_contam_ref_vNNNN',
;                         where NNNN is a 4-digit number.]
;                         This is the version number of the "XRT_contam"
;                         structure definition. In addition to being
;                         recorded in this field, this is also the
;                         "unique structure name" in the IDL sense.
;                         The value is initialized at creation. This
;                         field should NOT be changed.
;                     FCTM_STR_DESCR: (string scalar)
;                         This is a sentence or two that describes the
;                         purpose of this structure type. This field
;                         should NOT be changed.
;                     FILTER1: (string scalar)
;                         This is the name of the FW1 filter used
;                         in the calculation.  
;                     FILTER2: (string scalar)
;                         This is the name of the FW2 filter used
;                         in the calculation.  
;                     NAME: (string scalar)
;                         This is a name for this contamination layer
;                         thickness. This string should concisely
;                         identify the contamination layer (although
;                         it may not be unique). Some programs may
;                         refer to this string, so its usage should
;                         be regularized. (Compare to LONG_NAME.) This
;                         field MAY be changed, but the default is
;                         recommended.
;                     LONG_NAME: (string scalar)
;                         This is a longer string for the name for
;                         this contamination layer thickness. This
;                         field should not be referred to by software;
;                         it is intended to provide a more informative
;                         description for humans.  This field MAY be
;                         changed, but the default is recommended.
;                     MATERIAL: (string scalar)
;                         Name of substance or chemical compound forming
;                         the contamination layer. (NAME may or may
;                         not specify the substance's identity. MATERIAL
;                         should always specify the substance's
;                         identity.)
;                     DENS: (float scalar)
;                         Density of the contamination material named
;                         in the MATERIAL tag, and that was used to
;                         calculate the transmission function. The
;                         value must be consistent with the units named
;                         in DENS_UNITS.
;                     DENS_UNITS: (string scalar)
;                         Units of the value in the DENS tag. The units
;                         must be 'g cm^-3' (so that other programs
;                         can reliably interpret DENS).
;                     THICK: (float scalar)  (filter1+2 combined thickness) 
;                         Thickness of the contamination material named
;                         in the MATERIAL tag, and that was used to
;                         calculate the transmission function. The
;                         values must be consistent with the units named
;                         in THICK_UNITS.
;                     THICK_UNITS: (string scalar)
;                         Units of the value in the THICK tag. The
;                         units must be 'Angstroms' (so that other
;                         programs can reliably interpret THICK).
;                     THICK_TIME: (string scalar)
;                         This is the mission time for which the
;                         contamination thicknesses (tag THICK) were 
;                         calculated, as specified by INPUT1 and keyword
;                         INTYPE=0. It is possible that the thicknesses
;                         were asserted independent of a mission time
;                         (using INPUT1 and INTYPE=2), in which case
;                         the THICK_TIME tag may have an empty string
;                         value (''). The value should be in a string
;                         time format recognized by SSWIDL.
;                     DATA_FILES: (string array, [5])
;                         This is a list of filenames of reference
;                         data that were used in the specification of
;                         the contamination. It is primarily intended
;                         for listing any files that might be important
;                         for reference purposes.  This field should
;                         NOT be changed, but empty strings may be
;                         added to.
;                     HISTORY: (string array, [3])
;                         This text array is for XRT programs to record
;                         any instance in which they have modified the
;                         content of the "XRT_filt_contam" type of structure
;                         for this particular contamination description.
;                         On creation, a line is added for the creation
;                         of the "XRT_filt_contam" structure in
;                         <make_xrt_filt_contam.pro>.  An entry string is
;                         composed of (a) a program name, (b) the
;                         program's version/date, (c) colon separator,
;                         (d) Timestamp (in parentheses) of when the
;                         program completed the described action, and
;                         (e) a summation of what the program created
;                         or modified in the "XRT_filt_contam" structure.
;                         Values are inserted starting at the lowest
;                         address of this array. Remaining unused
;                         addresses are filled with the empty string.
;                         Filled strings should NOT be overwritten.
;                         Users should use the COMMENTS field to add
;                         their own notations to this structure.
;                     COMMENTS: (string array, [5])
;                         A tag for adding notations regarding this
;                         specific contamination layer and thickness.
;                         Users and programs are encouraged to put
;                         content in the lower addresses, and assign
;                         empty strings {''} to the higher, unused
;                         addresses.
;
;       QABORT      - [Optional] (Boolean) Indicates whether the program
;                     exited gracefully without completing. (Might be
;                     useful for calling programs.)
;                     0: Program ran to completion.
;                     1: Program aborted before completion.
;
; EXAMPLES:
;
;       This program is a subroutine of <make_xrt_wave_resp.pro>.
;
; COMMON BLOCKS:
;
;       none
;
; NOTES:
;
;       1) There are three levels of verbosity.
;          a) "verbose" = highest priority. All errors and messages are
;                         displayed. ("if q_vb")
;          b) "quiet" = lower priority. No errors or messages are
;                       displayed. ("if q_qt")
;          c) neither = lowest priority. All errors and some messages are
;                       displayed. ("if not q_qt")
;       2) This routine replaces <calc_xrt_effarea.pro>.
;
;
; CONTACT:
;
;       Comments, feedback, and bug reports regarding this routine may be
;       directed to this email address:
;                xrt_manager ~at~ head.cfa.harvard.edu
;
; MODIFICATION HISTORY:
;
progver = 'v2008-Sep-01' ;--- (M.Weber) Written. Derived from 
;                             <calc_xrt_effarea.pro>, v2007-May-15. 
progver = 'v2008-Oct-01' ;--- (M.Weber) Reviewed version.
progver = 'v2009-Nov-20' ;--- (S.Saar) Modfied to include the effect of 
;                             contamination on the filters. 
progver = 'v2025-Jan-24' ;--- (L.Guliano) Switched to linear instead of quad interpolation
;-
; =========================================================================


; === Initial setup ==============================

  ;=== Set Booleans which control print statements.
  ;=== Keyword "verbose" overrules "quiet".
  q_vb = keyword_set(verbose)
  q_qt = keyword_set(quiet) and (q_vb eq 0)


  ;=== Initialize program constants.
  prognam = 'MAKE_XRT_EA'
  prognul = '           '


  ;=== Announce version of program.
  if q_vb then box_message, prognam+': Running ' + progver + '.'
  if q_vb then print, prognam+': Performing initial setup...'


  ;=== Set some keyword Booleans.
  qstop    = keyword_set(qstop)
  qabort   = 0B
  qtype = keyword_set(intype)
  if qtype eq 0 then intype=0

  ;=== Some basic program values.
  nchn = n_elements(channels)


  ;; In this next bit, we define some structure templates
  ;; that will be used further on.

  ;=== Define the {XRT_filt_contam_ref} stucture.  *** new
  fctm_str_version = 'XRT_FILT_CONTAM_REF_V0001'
  fctm_ref = create_struct(name=fctm_str_version,                          $
                        'type', 'XRT_FILT_CONTAM_REF',                     $
             'fctm_str_version', fctm_str_version,                         $
               'fctm_str_descr', 'Provides description of a combined '     $
                                + 'filter contamination layer for an XRT ' $
                                + 'channel, without the transmission ' $
                                + 'function.',                         $
                     'filter1', '',                                    $
                     'filter2', '',                                    $
                        'name', '',                                    $
                   'long_name', '',                                    $
                    'material', '',                                    $
                        'dens', 0.0,                                   $
                  'dens_units', '',                                    $
                       'thick', 0.0,                                   $
                 'thick_units', '',                                    $
                  'thick_time', '',                                    $
                  'data_files', strarr(5),                             $
                     'history', strarr(3),                             $
                    'comments', strarr(5)                               )
  fctm_tagnames = tag_names(fctm_ref)

  ;=== Define the {XRT_contam_ref} stucture.  added "CCD" to ctm_str_descr
  ctm_str_version = 'XRT_CONTAM_REF_V0001'
  ctm_ref = create_struct(name=ctm_str_version,                        $
                        'type', 'XRT_CONTAM_REF',                      $
             'ctm_str_version', ctm_str_version,                       $
               'ctm_str_descr', 'Provides description of a '           $
                                + 'CCD contamination layer for an XRT '    $
                                + 'channel, without the transmission ' $
                                + 'function.',                         $
                        'name', '',                                    $
                   'long_name', '',                                    $
                    'material', '',                                    $
                        'dens', 0.0,                                   $
                  'dens_units', '',                                    $
                       'thick', 0.0,                                   $
                 'thick_units', '',                                    $
                  'thick_time', '',                                    $
                  'data_files', strarr(5),                             $
                     'history', strarr(3),                             $
                    'comments', strarr(5)                               )
  ctm_tagnames = tag_names(ctm_ref)


  ;=== Define the {XRT_eff_area} stucture.  altered eff_str_descr ***
  eff_str_version = 'XRT_EFF_AREA_V0001'
  eff_str = create_struct(name=eff_str_version,                            $
                        'type', 'XRT_EFF_AREA',                            $
             'eff_str_version', eff_str_version,                           $
               'eff_str_descr', 'Provides effective area for an XRT '      $
                                + 'channel, for a given thicknesses of the ' $
                                + 'CCD & filter contamination layers.',    $
                        'name', '',                                        $
                        'wave', fltarr(5000),                              $
                  'wave_units', 'Angstroms',                               $
                    'eff_area', fltarr(5000),                              $
              'eff_area_units', 'cm^2',                                    $
                      'length', 0L,                                        $
                     'history', strarr(3),                                 $
                    'comments', strarr(5)                                   ) 



  if q_vb then print, prognam+': Performing initial setup... OK'


; === Check inputs ===============================

  if q_vb then print, prognam+': Checking inputs...'

  ;; Only do a few simple checks.
  ;; INPUT1 and INTYPE are checked by <make_xrt_contam.pro>.
  ;; CHANNELS is (supposed to be) vetted by the parent routine 
  ;; <make_xrt_wave_resp.pro>, so the checks are cursory.
  ;; CONTAM is an output.

  ;=== Check that some input has been given.
  if (n_params() ne 2) then begin
    if (not q_qt) then box_message,                            $
        [prognam+': There should be exactly two input parameters:', $
         prognul+'  INPUT1 and CHANNELS.', $
         prognul+'  See program header. Aborting...'   ]
    qabort = 1B
    return, 0
  endif


  ;=== Cursory checks on CHANNELS input.
  ;; If CHANNELS is not a structure, then abort...
  if (datatype(channels) ne 'STC') then begin
    if (not q_qt) then box_message,                   $
      [prognam+': Input CHANNELS must be a structure. ', $
       prognul+'  See program header. Aborting...'     ]
    qabort = 1B
    return, 0

  ;; Else if CHANNELS is a structure...
  endif else begin

    ;; If CHANNELS doesn't have the TYPE tag, then abort...
    ss = where(tag_names(channels) eq 'TYPE', count)
    if (count eq 0) then begin
      if (not q_qt) then box_message,                   $
        [prognam+': Input CHANNELS must be a structure ', $
         prognul+'  of name "XRT_chn_config_vNNNN".', $
         prognul+'  See program header. Aborting...'     ] 
      qabort = 1B
      return, 0 

    ;; Else if CHANNELS does have the TYPE tag...
    endif else begin

;;      ;; If CHANNELS.TYPE isn't correct...
;;      if (channels[0].type ne 'XRT_chn_config') then begin
;;        if (not q_qt) then box_message,                   $
;;          [prognam+': Input CHANNELS must be a structure ', $
;;           prognul+'  of name "XRT_chn_config_vNNNN".', $
;;           prognul+'  See program header. Aborting...'     ]
;;        qabort = 1B
;;        return, 0
;;      endif
    endelse

  ;; All checks passed.
  endelse


  if q_vb then print, prognam+': Checking inputs... OK'


; === Get contamination structures. ===========================

  if q_vb then print, prognam+': Getting CCD contamination component(s)...'

  contam_in = make_xrt_contam(input1, channels, intype=intype, $
                              verbose=verbose, quiet=quiet,  $
                              qabort=qabort, qstop=qstop      )

  ;; Check whether subroutine succeeded.
  if qabort then begin
    if (not q_qt) then box_message,                             $
      [prognam+': The subroutine MAKE_XRT_CONTAM.PRO aborted.', $
       prognul+'  Aborting...'                                   ]
    qabort = 1B
    return, 0
  endif

  if q_vb then print, prognam+': Getting CCD contamination component(s)... OK'

; *** new

  if q_vb then print, prognam+': Getting filter contamination component(s)...'

  fcontam_in = make_xrt_filt_contam(input1, channels, intype=intype, $ 
                              verbose=verbose, quiet=quiet,  $
                              qabort=qabort, qstop=qstop      )

  ;; Check whether subroutine succeeded.
  if qabort then begin
    if (not q_qt) then box_message,                             $
      [prognam+': The subroutine MAKE_XRT_FILT_CONTAM.PRO aborted.', $
       prognul+'  Aborting...'                                   ]
    qabort = 1B
    return, 0
  endif

  if q_vb then print,prognam+': Getting filter contamination component(s)... OK'

; === Define and initialize the output structures. ============

  if q_vb then print, prognam+': Initializing output substructures...'

  ;=== Prepare the {XRT_contam_ref} structure array.
  contam_out = replicate(ctm_ref, nchn)
  struct_assign, contam_in, contam_out, /nozero
  ;; Rewrite some fields because they were overwritten...
  contam_out.type            = ctm_ref.type
  contam_out.ctm_str_version = ctm_ref.ctm_str_version
  contam_out.ctm_str_descr   = ctm_ref.ctm_str_descr

  ;=== Prepare the {XRT_filt_contam_ref} structure array.
  fcontam_out = replicate(fctm_ref, nchn)
  struct_assign, fcontam_in, fcontam_out, /nozero
  ;; Rewrite some fields because they were overwritten...
  fcontam_out.type            = fctm_ref.type
  fcontam_out.fctm_str_version = fctm_ref.fctm_str_version
  fcontam_out.fctm_str_descr   = fctm_ref.fctm_str_descr

  ;=== Prepare the {XRT_eff_area} structure array.
  eff_areas      = replicate(eff_str, nchn)
  eff_areas.name = channels.name + '; CCD contam = ' +         $
                   strcompress(contam_in.thick,/rem)  + ' ' + $
                   contam_in.thick_units + ' filter1+2 contam = ' + $
                   strcompress(fcontam_in.thick,/rem)  + ' ' + $
                   fcontam_in.thick_units + ' ' + fcontam_in.name
               

  if q_vb then print, prognam+': Initializing output substructures... OK'


; === Solve effective areas. =================================

  if q_vb then print, prognam+': Solving the effective areas...'

  wlen = channels.length
  clen = contam_in.length

  for ichn = 0,(nchn-1) do begin

    if q_vb then print, prognam+': Working on channel ' +   $
                        strcompress(ichn+1,/rem) + ' of ' + $
                        strcompress(nchn,/rem) + '.'

    wave1 = channels[ichn].wave[0:wlen[ichn]-1]
    cwave1 = contam_in[ichn].wave[0:clen[ichn]-1]

    ;; Make sure there is overlap between the grids.
    ss2 = where( (wave1 ge min(cwave1)) and (wave1 le max(cwave1)), $
                 count2                                              )
    if (count2 eq 0) then begin
      if q_vb then begin
        print, prognam+': The wavelength grids for CHANNELS[' + $
                          strcompress(ichn,/rem) + ']'
        print, prognul+'  and CONTAM['+strcompress(ichn,/rem)+ $
                          '] do not overlap.'
        print, prognul+'  Zeroing out the corresponding effective area...'
      endif
      eff_areas[ichn].wave      = 0.0
      eff_areas[ichn].eff_area  = 0.0
      eff_areas[ichn].length    = 0L

    ;; If the grids overlap, then continue with calculation.
    endif else begin

      ;; Establish the new mutual wavelength grid, wave2.
      wave2 = wave1[ss2]

      ;; Interpolate the contam grids onto wave2. 
      ;      **** (assume fcontam & contam on same grid)
      ; Updated 2025/01/24
      ctrans2 = interpol(contam_in[ichn].trans[0:clen[ichn]-1], cwave1, wave2)
      fctrans2 = interpol(fcontam_in[ichn].trans[0:clen[ichn]-1], cwave1, wave2)
      ;;;ctrans2 = interpol(contam_in[ichn].trans[0:clen[ichn]-1], $
      ;;;                   cwave1, wave2, /quad              )
      ;;;fctrans2 = interpol(fcontam_in[ichn].trans[0:clen[ichn]-1], $
      ;;;                   cwave1, wave2, /quad              )


      ;; Assign results into TR structure.
      eff_areas[ichn].wave[0:count2-1]     = wave2
      eff_areas[ichn].eff_area[0:count2-1] = channels[ichn].trans[ss2] $
               * fctrans2 * ctrans2 * channels[ichn].geom.aperture_area
      eff_areas[ichn].length               = count2

    endelse    ;; (wavelength grids overlap)

  endfor  ;;  (ichn, loop over channels)

  if q_vb then print, prognam+': Solving the effective areas... OK'


; === Finish =====================================

  get_utc, utc, /stime
  hist_string = prognam+' '+progver+': ('+utc+' UTC) Generated {' $
                + eff_areas.type+'} structure with name "'        $
                + eff_areas.name+'".'
  eff_areas.history[0] = hist_string

  if q_vb then box_message, prognam+': ... Finished.'

  if qstop then stop

  return, eff_areas


END ;======================================================================
