;+
; NAME:
; EVAL_LINE_COMPLEX
;
; PURPOSE:
; This function returns a line template complex read from the input template
; file.
;
; CATEGORY:
; XRAY, GAMMA_RAYS, SPECTRUM, SPEX
;
; CALLING SEQUENCE:
; Meant to be called via line_complex.
;
; INPUTS:
;   energy_bins - independent variable, nominally energy in keV under SPEX
;   template_file - template file to read parameters from.  Each file should
;     be a text file with one line per row, with each line having the
;     relative flux, line center,  and line width.
;
; OUTPUTS:
;   result - photons/keV for each bin.  The final result is normalized to
;            1 photon/keV.
;
; OUTPUT KEYWORDS:
;   ERR_MSG - string containing error message.  Null if no error occurred.
;   ERR_CODE - [0 / 1] if an error [did / did not] occurr.
;
; COMMON BLOCKS:
; LINE_COMPLEX_COM
;
; CALLS:
; avg
; f_nline
; rd_tfile
;
; WRITTEN:
; Paul Bilodeau, NASA/GSFC-RITSS, 22-June-2001 - documentation and initial 
; debugging.
;
; MODIFICATION HISTORY:
;  20-aug-2002, Paul Bilodeau - rewrote for speed, efficiency, and
;    correctness of normalization factor.  Added SIGTHRESH keyword.
;  12-nov-2002, Paul Bilodeau - use f_gauss_intg, change _EXTRA to
;    _REF_EXTRA and pass _ref_extra on to f_nline.
;
;-
;------------------------------------------------------------------------------
FUNCTION eval_line_complex, energy_bins, $
                            template_file, $
                            ERR_MSG=err_msg, $
                            ERR_CODE=err_code, $
                            _REF_EXTRA=_ref_extra

err_msg = ''
err_code = 1
result = 0.

CATCH, err
IF err NE 0 THEN BEGIN
    err_msg = !err_string
    RETURN, 0.
ENDIF
 
params = rd_tfile( template_file, 3, /CONVERT )

n_templates = N_Elements( params[0,*] )
use = Where( params[2,*] GT 0., n_use )

IF n_use EQ 0 THEN BEGIN
    err_msg = 'No sigmas are positive - cannot evaluate.'
    RETURN, 0.
ENDIF

par2use = Reform( params[*,use], n_use*3 )

result = f_div( f_nline( energy_bins, par2use, _EXTRA=_ref_extra ), $
                Total( params[0,use] ) )

err_code = 0

RETURN, result

END
