
;+
; NAME:
;   SPEX_PROC
; PURPOSE:
;   Run the SPEX spectral analysis package as a procedure
; CALLING SEQUENCE:
;spex_proc, command=command, script_commands=script_commands, $
;  prm_spex=prm_spex, prm_spex_info=prm_spex_info, cosine=cosine, $
;  ut=ut, flux=flux, eflux=eflux, ltime=ltime, rate=rate, erate=erate, back_order=back_order, $
;  backgrnd=back, eback=eback, tb=tb, $
;  edges=edges , e_in=e_in, drm=drm,  obsi=obsi, convi=convi, eobsi=eobsi, backi=backi, ebacki=ebacki, $
;  live=live, in_start=in_start, in_end = in_end, iegroup=iegroup, $
;  need_accum=need_accum, need_nw_bck=need_nw_bck, uncert=uncert, $
;  dir_queue=dir_queue, files=files, _extra=_extra
;
; input and output
;   These are all of the important input and output variables in
;   the SPEX environment:
; Parameters::::::
;   These are the parameters:
;   QUIET CHECK_DEFAULTS DFLTS_FILE DATA_TIPE _1FILE _2FILE DIRECTORY FLARE
;   DET_ID PSSTYLE UTS UTE T_HIST_MODE
;   ENERGY_BANDS SCALE_BANDS EPLOTS TH_YTYPE TH_YRANGE IAVG F_MODEL APAR
;   FREE UNCERT IFIRST ILAST RANGE_LO
;   RANGE_HI ERANGE SUMFIT SP_XTYPE SP_YTYPE SPXRANGE SPYRANGE MORE_INFO
;   DDIRECTORY DFILE SFILE HIGH_DRM
; APAR           Fit Model Initial Parameters, referenced to FIT_MODEL,
;                the model function
; DATA_TIPE      Data_tipe(0) - Instrument, e.g. 'BATSE'
;        Data_tipe(1) - Data Mode   e.g. 'CONT', 'SHERS', 'HERS'
; DET_ID     Detector ID, for BATSE 0-7
; DFLTS_FILE     File with defaults for parameters from LIST command.
; ENERGY_BANDS   Energy bands (keV) for display in GRAPH command.  Grouped by twos.
; EPLOTS         Logical.  If set, then display error bars in GRAPH command.
; ERANGE         Energy interval used for fitting.
; FLARE          BATSE archive flare number.
; FREE           Logical array.  Set to 0 or 1 corresponding APAR parameter in F_MODEL is
;        fixed(0) or free(1).
; F_MODEL    Name of function used in fitting.
; HIGH_DRM       Logical.  If set, then the high energy versions of the DRMs are used in the
;            BUILD_DRM command.
; IAVG           Interval averaging parameter.  Used under SELECT_INTERVAL.  IAVG consecutive intervals
;        are grouped together when using REGULAR style.
; IFIRST         First accumulation to use for fitting and PHOTON_SPECTRUM display.
; ILAST          Last accumulation to use for fitting.
; QUIET          If set, it reduces the reporting during fitting.
; RANGE_HI       High boundaries for fitting parameters, apar, RANGE(*,1)
; RANGE_LO       Low boundaries, RANGE(*,0)
; SCALE_BANDS    Multiplicative factors applied to light curve bands in GRAPH.
;        Referenced to ENERGY_BANDS or first four channels in CHAN_MASK
; SPXRANGE       If non-zero, this is the xrange used in spectral plotting.
; SPYRANGE       If non-zero, this is the yrange used in spectral plotting.
; SUMFIT         If not set, then initial fit parameters are taken from the
;        previous interval, apar_arr(*,i-1).  If set, then the initial fit
;        parameters are taken from the previous fit to the ith interval
;        in apar_last(*,i).
; T_HIST_MODE    TIME_HISTORY and GRAPH display mode.
;        FLUX for counts/s/cm2/keV
;        COUNTS for counts/s
; UTE            Timerange upper bound in string format. Normally set with Zoom command.
; UTS            Timerange lower bound.
; Variables not contained in PRM_SPEX but found in SPEX_COMMONS.
; These next 4 variables span the entire data set as read in:
; The data are dimensioned in Number_Energy_bin X Number_Time_bin

; FLUX      Input count rate, channels by intervals, in counts/s/keV/cm2
;       including livetime correction
; EFLUX     1-sigma uncertainty on FLUX, same units, includes uncertainty from
;       background algorithm and Poisson statistics
; RATE      Background subtracted count rate, channels by intervals, in counts/s/keV/cm2
;       including livetime correction
; ERATE     1-sigma uncertainty on RATE, same units, includes uncertainty from
;       background algorithm and Poisson statistics
; BACK      Background count rate, channels by intervals, in counts/s/keV/cm2
;       including livetime correction
; EBACK     1-sigma uncertainty on BACK, same units, includes uncertainty from
;       background algorithm and Poisson statistics
;
; The next set of variables apply globally to the input data set
; EDGES     PHA energy edges, low and high edges in keV, dimensioned 2 xNumber_energy_bins
; UT        Dimensioned 2 x Time_bin, the start and stop of each interval in seconds
;       measured from 1-Jan-1979
;       (really 86400.*number_days from 1-jan-1979+seconds_of_day).
; AREA      Geometric detector area, a fixed scalar regardless of angle or energy
; DELTA_LIGHT   PHA energy width for each energy_bin, in this case it is edges(1,*)-edges(0,*)
; COUNT_2_FLUX  a vector, DELTA_LIGHT * AREA
; DRM           Detector response matrix, PHA_energy_bins x number_input_photon_energies.
;       The input_photon_energies are in E_IN, and should not be confuse with EDGES.
;       Defined as the counts/cm2/keV per incident photon/cm2 for each cell.
; DET_ID    The detector ID, a number ranging from 0-7 for BATSE
; FILES     The data files used in the session.

; The next 7 variables span the data selected for spectral fitting.
; The data are dimensioned in Energy_bin X Accumulation_interval
;
; OBSI      Average count rate, channels by intervals, in counts/s/keV/cm2
;       including livetime correction
; EOBSI     Uncertainty on OBSI, channels by intervals, in counts/s/keV/cm2
;       including livetime correction
; BACKI     Average background rate, channels by intervals, in counts/s/keV/cm2
;       including livetime correction

; EBACKI    Uncertainty on BACKI, channels by intervals, in counts/s/keV/cm2
;       including livetime correction
; CONVI     Conversion factor, dimensionless ratio, the pseudo-effective area,
;       defined for the fitted model spectrum as the ratio of
;       the expected_count_rate to the photon_flux integrated over each
;       energy_bin.
;
; PHOTONS   defined as (OBSI-BACKI)/CONVI
; EPHOTONS  the 1-sigma uncertainty on PHOTONS

; The next two variables also are generated by selecting fitting time intervals

; APAR_ARR      Fit Model Initial Parameters, referenced to FIT_MODEL,
;               the model function dimensioned Number_parameters X Accumulation_interval
; XSELECT   The time in seconds from the start of the day(at the start of the data)
;       for each accumulation interval, dimensioned 2 x Accumulation_interval
;
; COMMAND
; SCRIPT_COMMANDS
; BACK_ORDER     Polynomial order for background construction
;
; IEAVG          Spectral interval averaging parameter.  For display purposes only at present.  Used
;        under SPEC_BANDS command.
; ITER           Number of outside loops on Curvefit where conversion factors are recomputed.
; NITER          Number of loops inside of Curvefit.
; UNCERT         Minimum uncertainty in FLUX bin as a fraction of FLUX.
;
; PRM_SPEX       Structure with display and control parameters
; IN_START   Start reading data file at in_start, e.g. 30-jun-91 02:55:00
; IN_END     Read file until in_end.
; Need_accum     if set, then use iselect to integrate over time to create OBSI, EOBSI, etc
; Need_nw_bck    if set, background subtraction is needed
; DIR_QUEUE      Hierarchical selection of directories to search for data files, including wildcards
;        e.g. ['????? /usr5/com/schwartz/db_?????/', '/usr6/com/schwartz/db_?????/']
; APAR_LAST      Fit Model parameters for last fit to each interval.
; COSINE         Cosine of the angle between the detector normal and the photon source.
; E_IN           Incident energies defined for DRM.
; IEGROUP    Channel number boundaries of spectral channels grouped together.
; ISELECT        Index of interval boundaries (referenced to FLUX) of accumulation intervals.
;        The ith interval starts at the leading edge of ISELECT(0,i) and ends at the leading
;        edge of ISELECT(1,i).
; LIVE           Live time in seconds of each accumulation interval.
; LTIME          Live time in seconds of each FLUX observation interval
; TB             Boundaries of background intervals with same reference
;        as UT (sec)
; MODIFICATION HISTORY:
;   ras, 15-apr-94
;   ras, 18-sep-95, changed to @spex.pro from @spex to help idl find it.
;-
;
pro spex_proc, input_line=input_line, $
               gui=gui, $
               cmode=command_mode, $
               bang_out=bang_out

@spex_commons
;+
;
; NAME:
;	SPEX_COMMONS
;
; PURPOSE:
;	Data and Option storage common blocks for SPEX
;
; CATEGORY:
;	SPEX
;
; CALLING SEQUENCE:
;	Not a procedure, code to be included using "@spex_commons"
;
; CALLS:
;	none
;
; INPUTS:
;       none explicit, only through commons;
;
; OPTIONAL INPUTS:
;	none
;
; OUTPUTS:
;       none explicit, only through commons;
;
; OPTIONAL OUTPUTS:
;	none
;
; KEYWORDS:
;	none
; COMMON BLOCKS:
;	SPEX_PROC_COM - Input and Processed Data Arrays
;	SPEX_SETUP_COM- Control Options
;	SPEX_HOLD_COM - Used for merging data input streams
;
; SIDE EFFECTS:
;	none
;
; RESTRICTIONS:
;	none
;
; PROCEDURE:
;	Common blocks only, used in SPEX_PROC, SPEX_CURRENT, SPEX_SAVE
;				    SPEX_SAVE_DATA, SPEX_CURRENT, SPEX
;				    OPTION_CHANGER, SPEX_SOURCE, HELP_MERGE
;				    SPEX_DELETE, SPEX_MERGE, SPEX_HOLD
;
; MODIFICATION HISTORY:
;	Documented ras, April 1996
;	Version 2, ras, Added HANDLES, 3 April 1996, last_plot
;
;	Version 3, ras, Added HANDLES, 15 May 1996, added p_read_data and
;	moved p_drm_reader
;	Version 4, ras, 18-Jul-1997, added erange and flare
;	19-mar-02, ras, pyb, added spex_debug, spex_obj to
;		support catch and objects
;       17-sep-2002, PB, changed SPEX_DEBUG to Boolean flag.
;-


;
;COMMON BLOCKS FOR WSPEX.PRO AND SPEX_PROC.PRO
;
common spex_proc_com,  cosine, det_id,  ut, flux, eflux, ltime, rate, area, $
  datamode, title, count_2_flux, uflux, erate, handles, last_plot, $
  back, eback, wback, tb, def_tb, xselect, iselect, wint, wuse, edges, $
  delta_light, edg_units, e_in, eff, drm, obsi, convi, eobsi, backi, ebacki, $
  live, start_time_data, end_time_data, iegroup,  range, apar, apar_arr, $
  apar_last, apar_sigma, chi,  batse_burst, erange, flare, spex_debug, spex_obj

common spex_setup_com, noreadinput, style_sel, setup_sys, prompt, nolist, $
  comments, dflts_file, files, families, parameters, prm_spex, prm_spex_sav, $
  prm_spex_info, tavg, uncert, y_spectitle, script_opt1, script_opt2, $
  standard_types, back_order,  backscale, bdata, psfile, use_band, dir_queue, $
  need, last_found, last_read, wtitles, gaction, sensitive, p_drm_reader, $
  p_read_data, gdaction, goaction,  plotbuffer, bang_enter, nowidget, $
  sher_only, merge_list, mscript

;this common block will allow merging of data_tipes
common spex_hold_com, flux_h, eflux_h, edges_h, count_2_flux_h, $
  delta_light_h, e_in_h, det_id_h, ut_h, drm_h, ltime_h, area_h, source_h, $
  source, insource, insource_h, edges_drm, edges_drm_h, more_types
;
;

common wspex_common,  main_menu, info_base, new1, new2, new3, new4
if keyword_set(gui) and n_elements(main_menu) gt 0 then begin
    widget_control, main_menu, /hourglass ,sensitive=fcheck(sensitive,0)
    endif
bang_out = fcheck(bang_enter,0)

noreadinput = fcheck(gui,0) or fcheck(command_mode)
if noreadinput and (fcheck(input_line,''))(0) ne '' then printx, input_line
if n_elements(e_in) ne 0 then edge_products, e_in, gmean=em_in, wid=w_in
if n_elements(edges) ne 0 then edge_products, edges, mean=emdge, width = wedge
if n_elements(setup_sys) ne 0 then begin
    !x.margin=setup_sys.xmargin
    !y.margin=setup_sys.ymargin
    !p.charsize=setup_sys.pcharsize
    endif

spex_debug = Strmid( Strupcase( get_logenv('SPEX_DEBUG') ), 0, 3 )
spex_debug = spex_debug EQ 'YES' OR spex_debug EQ 'Y' OR spex_debug EQ '1'
IF spex_debug THEN BEGIN
    MESSAGE, 'SPEX DEBUGGING ENABLED.', /CONTINUE
    CATCH, err
    IF err NE 0 THEN MESSAGE, !err_string, /CONTINUE
ENDIF ELSE CATCH, /CANCEL

if n_elements(comments) ne 0 then goto, not_first_time

@spex.pro
