;+
; NAME:
;	SPEX_SUMMARY
; PURPOSE:
;	To save and restore variables defined in a SPEX session
; CATEGORY:
;	I/O
; CALLING SEQUENCE:
;	spex_summary,sumfile,data_tipe,flare,dflts_file,$
;	apar_last=apar_last,chi=chi,xselect=xselect,iselect=iselect,tb=tb, $
;	prm_spex=prm_spex,style_sel=style_sel,$
;	input_line=input_line,check_defaults=check_defaults,/save
; PROCEDURE:
;    Set sumfile and dflts_file so that they have the same root name
;	    with the appropriate suffixes
;    Save:
;    	if a paramter to be saved isn't defined define it
;	save parameters
;	run RESTORE_DFLTS using INPUT_LINE
;    Restore:
;	restore SumFile
;	check to see whether background and interval selection
;	    have been done
;	run SAVE_DFLTS and other commands to set up data using INPUT_LINE
;
; INPUTS:
;   Inputs used to name IDL save file
;    SUMFILE     Name of file in which to store parameters
;		 Basis of name for save file used here.
;    DATA_TIPE   Data_tipe(0) - Instrument, e.g. 'BATSE'
;                Data_tipe(1) - Data Mode   e.g. 'CONT', 'SHERS', 'HERS'
;    FLARE       flare number.
; OUTPUTS:
;    DFLTS_FILE  Name of file in which to store defaults (save_dflts)
; KEYWORDS:
;    Parameters to be saved/restored:
;    APAR_LAST      Fit Model parameters for last fit to each interval.
;    CHI	    Chi-squared vaules
;    XSELECT        Time boundaries on accumulation intervals referenced to the
;		    same base as UT
;    ISELECT        Index of interval boundaries (referenced to FLUX) of
;		    accumulation intervals.
;    TB             Boundaries of background intervals with same reference
;                   time given by ATIME( getutbase(0))
;    PRM_SPEX       Structure with display and control parameters
;    Other:
;    SAVE           Save Parameters (with save_event)
;    RESTORE        Restore Paramters (with restore_event)
;    INPUT_LINE     Output - commands to be performed after spex_summary
;    CHECK_DEFAULTS Given so that it can be reset to original value
;    STYLE_SEL      If spectral intervals are in the file this is set to
;			'discrete'
;
; COMMON BLOCKS:
;	None.
;
; SIDE EFFECTS:
;	Changes name of dflts_file so that it has a .dflt extension
;
; RESTRICTIONS:
;	None.
;
; MODIFICATION HISTORY:
;	Written: TAK, September, 1994
;	mod, ras, oct 1994
;	Version 3, richard.schwartz@gsfc.nasa.gov, made file finding more robust.
;	11-jan-2001. Added code to support up to 60 values in a parameter field.
;; Version 4, ras, 6-nov-2002, enable up to 200 parameters in spex after 5.1
;-
pro spex_summary,sumfile,data_tipe,flare,dflts_file,$
	apar_last=apar_last, chi=chi, xselect=xselect,iselect=iselect,$
	tb=tb,prm_spex=prm_spex,style_sel=style_sel,$
	save=save, restore=restore,input_line=input_line,$
	check_defaults=check_defaults


;extract directory from prm_spex
directory = spex_current('sumdirectory')
det_id    = spex_current('det_id')

;determine file name

if strupcase(sumfile) eq 'AUTO' then begin
    sumfile = arr2str(data_tipe,delim='_')+'_'+strtrim(flare,2)+'_'+strtrim(det_id,2)
    dflts_file = sumfile
endif

break_file, sumfile,disk_log, dir, filnam, ext
if ext eq '' then sumfile = sumfile + '.sum'

break_file, dflts_file,disk_log, dir, filnam, ext
if ext eq '' then dflts_file = dflts_file + '.dflt'

on_ioerror, error_mess

;Save
if keyword_set(save) then begin
					;make sure all parameters are defined
    if n_elements(apar_last) eq 0 then apar_last=0
    if n_elements(chi) 	     eq 0 then chi=0
    if n_elements(xselect)   eq 0 then xselect=0
    if n_elements(iselect)   eq 0 then iselect=0
    if n_elements(tb)        eq 0 then tb=dblarr(2, 6, 5)
    if n_elements(prm_spex)  eq 0 then prm_spex=0
;save parameters
    error_text = 'Error saving summary file:'+ sumfile
    save,/xdr,file = concat_dir(chklog(directory), strlowcase(sumfile)),$
	apar_last,chi,xselect,iselect,tb,prm_spex
    printx, 'Writing event file, '    + concat_dir(chklog(directory), strlowcase(sumfile))
    input_line = 'save_dflts'

endif

if keyword_set(restore) then begin
				  ; open and restore file
    temp = loc_file( path = ([curdir(),directory])[keyword_set(directory)], strupcase(sumfile), count=r)
    if r eq 0 then begin
	temp = loc_file(path =([curdir(),directory])[keyword_set(directory)] , strlowcase(sumfile), count=r)

	if r eq 0 then begin
	    printx, 'Cannot find event summary file: '+ concat_dir(chklog(directory), strlowcase(sumfile))
	    return
	endif
    endif
    if r ge 1 then begin
        on_ioerror, error_mess
        error_text = 'Error restoring summary file: '+sumfile
	if exist(prm_spex) then prm_spex_dest = prm_spex
	if since_version('5.1') then restore, temp(0), /relaxed else restore, temp(0)
	text=['Restoring file '+temp(0)]
	;PRM_SPEX_DEST allows the change in the length of prm(i).val to increase from 20 in {param_structure2}
	;to 60 in {param_structure3}
	;
	if exist(prm_spex_dest) then begin
		for i=0,n_elements(prm_spex)-1 do prm_spex_dest[i].val = prm_spex[i].val
		prm_spex = prm_spex_dest

		endif
        dflts_file = prm_spex(where(prm_spex.nam eq 'DFLTS_FILE')).val(0)
        printx, 'DEFAULTS FILE TO BE RESTORED: '+dflts_file
    endif
        				;run script to read data and setup
					;background and spectral intervals
;the defaults file is restored several times to recover values that are changed by the
;time_history command, which changes the energy bands, and the background command which
;changes the values in tb
    script_commands=['restore_dflts','time_history','restore_dflts','check_defaults,0','zoom']
    if min(tb) ne max(tb) then $
	script_commands=[script_commands, 'background,auto'] $
    else text=[text,'No background intervals stored in event file.']
    if (n_elements(xselect) gt 1) and (n_elements(iselect) gt 1) then begin
	script_commands=[script_commands,'select_interval']
        style_sel='discrete'
    endif else text=[text,'No spectral intervals stored in event file.']
    script_commands=[script_commands,'Check_defaults,'+string(check_defaults)]
    text=[text,script_commands]
    printx,text
    input_line = arr2str(script_commands,delim = '!!')
endif

on_ioerror, null
return

error_mess:
  printx,error_text
  on_ioerror, null

end
