; Copyright (c) 1998-2015 C. Zimba & A.P. Hitchcock  All rights reserved
;+
; NAME:
;	ZSTACK_SAVE.PRO
;
; LAST CHANGED: ----------------------------------- 27-Jul-15
;
; PURPOSE:
;	Save images after alignment using ZSTACK_ANALYZE
; AUTHORS:
;	Carl G. Zimba (Photons UnLimited),
;	Partially derived from previous code by Chris Jacobsen (SUNY - Stonybrook)
; CATEGORY:
;	Data analysis.
; CALLING SEQUENCE:
;	zstack_save
; INPUTS:
;	NONE
; KEYWORD PARAMETERS:
;	NONE
; OUTPUTS:
;	NONE
; COMMON BLOCKS:
;	zstack_common	:
;		data_source				:	type of x-ray microscopy data: STXM:1, SXM:2, SM:3, ALS:4, POLY:5
;		data_directory				:	directory of data files
;		image_stack				:	3-D matrix of multiple x-ray microscope images
;		filename_list				:	list of filename corresponding to images in image_stack
;		ev_list					:	list of x-ray energies corresponding to images in image_stack
;		msec_list					:	list of dwell times corresponding to images in image_stack
;		filename_display_list			:	list of filename, x-ray energy, and dwell time corresponding to images in image_stack
;		displayed_file_index			:	index in image_stack, filename_list, msec_list, and filename_display_list currently being displayed or processed
;		n_files					:	number of images
;		list_filename				:	name of file to save or retrieve list of data files
;		shift_filename				:	filename of alignment shifts
;		x_shift					:	array of x-coordinate alignment shifts
;		y_shift					:	array of y-coordinate alignment shifts
;		data_shifted				:	0: data was not shifted and should not be clipped, 1: data was shifted and should be clipped, -1: denotes ZSTACK_PROFILE.PRO is being run as a stand-alone procedure
;		n_clipped_cols				:	number of columns in clipped image
;		n_clipped_rows				:	number of rows in clipped image
;		clipbox					:	vector of four points defining dimensions of region unclipped by alignment: [xleft,xright,ybot,ytop]
;		dragbox					:	vector of four points defining dimensions of region selected by box_cursor: [xleft,xright,ybot,ytop]
;	zstack_spectra_common
;		zstack_spectra_par			:	variables controlling ZSTACK Spectra dialog window
;		zstack_save_par				:	variables controlling ZSTACK Save dialog window
;		roi_index					:	vector of pixels corresponding to regions of interest for all i spectra
;		i_roi						:	vector of pixels corresponding to region of interest for current i spectrum
;		n_roi						:	number of regions of interest defined for i spectra
;		i0_roi					:	vector of pixels defining region of interest for i0 spectrum
;		is_i0_roi					:	Type of region of interest: 0: i0, 1: i
;		spectrum					:	2-D matrix (j,k) of spectra corresponding to defined regions of interest, j=0: i0 spectrum, j=1-14: i spectra, k corresponds to x-ray energy of image
;		save_spectra_type			:	Type of file to save spectra as:
;		spectra_filename_header		:	base filename of spectra and regions of interest to be saved on ZSTACK Spectra dialog window
;		roi_filename				:	filename for storage and retrieval of regions of interest points
;		save_filename_header			:	base filename of images to be saved on ZSTACK Save dialog window
;		i0_filename				:	base filename of i0 spectrum to be retrieved
;		i0_filetype				:	Type of file of retrieved I0 spectrum:	RAW, XAS, CSV
;		i_roi_color_index			:	vector of indices of colors for display of regions of interest for i spectra
;		i0_roi_color_index			:	color index for display of region of interest for i0 spectrum
;		nonintegral_zoom_data			:	scaled byte image used when image_zoom is non-integral
;	zstack_display_common
;		zstack_display_par			:	variables controlling ZSTACK Display dialog window
;		image_zoom					:	zoom factor for displaying images
;		subimage_zoom				:	zoom factor for subimages
;		movie_delay				:	delay used to display movie images of data stacks, dependent upon machine speed
;		disp_min					:	minimum percentage intensity for display of images
;		disp_max					:	maximum percentage intensity for display of images
;		disp_gamma					:	gamma factor for display of images
;		spectrum_display			:	Display spectra as: 1: Single Beam, 2: Percent Transmittance, 3: Absorbance
;		spectrum_offset				:	Offset used to plot spectra
;		init_zoom					:	initial zoom factor for displaying images (used in ZSTACK_SAVE and ZSTACK_TUNE)
;		movie_active				:	movie of images is active: 0: NO, 1: YES
;		profile_zoom				:	zoom factor for file number axis on profile images
;		image_range				:	scale images using: 0: intensity range of each image, 1: intensity range of full image stack
;		image_ratio				:	Display images normalized by: 0: inv_image_stack, 1: i0 spectrum
;		ratio_image_index			:	index of image to use when ratio images to a constant image
;		image_scale				:	Display images normalized by: 0: inv_image_stack, 1: i0 spectrum
;		image_invert				:	invert color bar: 0: NO, 1: YES
;		temp_old_display			:	initial array of display parameters, set at beginning of ZSTACK_DISPLAY
;		temp_new_display			:	array of display parameters updated as display options are changed
;		zstack_subroutine			:	subroutine from which ZSTACK_DISPLAY was called
;		plot_x_min					:	mimimum x-ray energy value to plot spectra
;		plot_x_max					:	maximum x-ray energy value to plot spectra
;		plot_y_min					:	mimimum intensity value to plot spectra
;		plot_y_max					:	maximum intensity value to plot spectra
;		x_autoscale				:	autoscale x-ray energy scale: 0: NO, 1: YES
;		y_autoscale				:	autoscale spectra intensity scale: 0: NO, 1: YES
;	zstack_color_common
;		bottom_color_index			:	index of lowermost color of gradient colorscale
;		top_color_index				:	index of uppermost color of gradient colorscale
;		black_color_index			:	index of black color
;		white_color_index			:	index of white color
;		plot_bkgd_color_index			:	color index for plot background, either black or white
;		plot_axes_color_index			:	color index for plot axes, either whilte or black
;		image_border_color_index		:	color index for image border in zstack_buildlist and zstack_profile dialog windows
;		dragbox_color_index			:	color index for dragbox used to define subregion for alignment
;		corr_ctr_color_index			:	color index for crosshair showing center of correlation function
;		corr_max_color_index			:	color index for crosshair showing maximum of correlation function
;		x_shift_color_index			:	color index for plotting of x-shift
;		y_shift_color_index			:	color index for plotting of y-shift
;		shift_cursor_color_index		:	color index for cursor in shift plot, indicating file number
;		tune_fiducial_color_index		:	color index for fiducial points in closeup of shifted image in zstack_tune dialog window
;		spectra_color_index			:	color indices (14) for plotting of spectra
;		spectra_cursor_color_index		:	color index for cursor in spectra plot, indicating x-ray energy
;		profile_color_index			:	color index for plotting of intensity profile and cursor in profile image indicating row or column
;		profile_cursor_color_index		:	color index for cursor in profile image, indicating x-ray energy
;		profile_spectrum_color_index	:	color index for plotting of profile spectrum
;		test1_color_index			:	color index #1 for testing
;		test2_color_index			:	color index #2 for testing
;		test3_color_index			:	color index #3 for testing
; SIDE EFFECTS:
;
; RESTRICTIONS:
;
; PROCEDURE:
;   Called from within ZSTACK_SPECTRA.PRO.
; EXAMPLE:
;
; MODIFICATION HISTORY:
;   25-Mar-1998 - now works with 24 bit graphics, CJJ
;   24-Jul-1998 - two changes (based on suggestions by Adam
;     Hitchcock, but the implementations here are my own) CJJ :
;     1. allow user to read in i0 files from an ascii file of
;        (line by line) values of ev, khz.  The file is used
;        only if it spans a larger range of eV values than the
;        images in the stack span.
;     2. Click on the spectrum to change the file which is displayed
;   14-Aug-1998 - now if there's an alignment file, read it in and
;     apply it but STILL give the user the chance to align the stack.
;     This allows one to (for example) first align a stack manually,
;     and then do an automatic alignment over a restricted shift
;     range to "refine" the alignment. CJJ
;   28-Aug-1998: with IDL 5.1 the way 24 bit graphics is handled is
;     now different - need to invoke device,decomposed=0, CJJ
;   31-Aug-1998: Allow saving and reading of stack files as XDR data,
;     don't read ROI file by default on startup, use zoom=1 unless
;     explicitly told otherwise, have alignment shifts saved by
;     this program rather than by alignment programs, allow clipping
;     of data to exclude shift boundaries, CJJ
;   27-sep-1998: but tvrd() works differently on different devices
;     so need to write images for GIF files to Z buffer, CJJ
;   13-oct-1998: Save many images at once, start to work on
;     ratio image stuff, CJJ
;
; Modified 20feb99, CGZ
; Extensively modified and rewritten STACK_ANALYZE.PRO to form ZSTACK_ANALYZE.PRO
; Changes and additions are numerous:
;
; All procedures and common variables starting with 'stk' were changed to 'zstack'
; so that the existing routine, STACK_ANALYZE.PRO, can be run in parallel
;
; Reorganized STACK_ANALYZE.PRO so that
;	spectral analysis is done with ZSTACK_SPECTRA and zstack_spectra_* procedures
;		spectra and regions of interest are saved with ZSTACK_SPECTRA
;	saving of image data is done with ZSTACK_SAVE and ZSTACK_SAVE_* procedures
;
; Procedures have been modified, added, eliminated as below:
;	zstack_save_prep		:	formerly stk_anl_graphics
;	zstack_save_imgdisp		:	formerly stk_anl_imgdisp
;	zstack_save_plotspectrum	:	formerly stk_anl_plotspectrum
;	zstack_save_clip_data		:	formerly stk_anl_clipdata
;	zstack_save_desensitive	:	new, adapted from stk_anl_desensitive
;	zstack_save_sensitive		:	new, adapted from stk_anl_sensitive
;	zstack_save_gifimage		:	stk_anl_savegifimg
;	zstack_save_gifmovie		:	stk_anl_gifmovie
;	zstack_save_stack_data	:	formerly stk_dat_savefile
;	zstack_save_event		:	new, adapted from stk_anl_event
;	zstack_save			:	new, adapted from stack_analyze
;	stk_aln_savefile		:	eliminated, moved to ZSTACK_ALIGN.PRO (zstack_align_save_shift)
;	stk_dat_readfile		:	eliminated
;	stk_anl_readroi			:	eliminated
;	stk_anl_roi_event		:	eliminated, replace with CW_DEFROI.PRO
;	stk_anl_roi			:	eliminated, replace with CW_DEFROI.PRO
;
; Functions of procedures are now:
;	zstack_save_prep		:	sets color table and color indices and defines common variables
;	zstack_save_imgdisp		:	displays images and shift plot
;	zstack_save_plotspectrum	:	displays extracted spectra
;	zstack_save_clip_data		:	defines area of images not clipped by alignment shift
;	zstack_save_desensitive	:	deactivate features on Stack Save dialog window
;	zstack_save_sensitive		:	activate features on Stack Save dialog window
;	zstack_save_gifimage		:	save *.gif image of stack data
;	zstack_save_gifmovie		:	save *m.gif movie of stack data
;	zstack_save_stack_data	:	save stack data as file (for both clipped and unclipped)
;	zstack_save_event		:	event routine for zstack_save
;	zstack_save			:	main procedure for saving images and stack data sets
;
; Modified user interface window to include
;	display and movie of image and clipped image
;		regions of interest are plotted on both image and clipped image
;		cursor bar added to plot of spectra highlighting energy and intensity position
;			during movie or static display
;		eliminated text embedded in image, replaced it with text fields in dialog window
;	displayed file can be selected either using file list or spectral plot
;		clicking on spectral plot, prints file info and spectral intensity in Output Log
;	text fields added to display image information during movie or static display
;		this replaces text as part of image implemented in STACK_ANALYZE.PRO
;	eliminated "Add I Pixel" and "Add I0 Pixel" since it is embedded part of CW_DEFROI.PRO
;	eliminated ratio image feature - may restore later
;	eliminated IDL Slicer feature - may restore later
;	"Load New Color Table" option added
;		can change the color table in either ZSTACK_SPECTRA, ZSTACK_SAVE, or ZSTACK_PROFILE
;	saving of spectra in multiple formats: *.xas, *.spc, *.gif
;	added ability to extract spectra from multiple regions simultaneously (up to 14 spectra)
;
; Replaced stk_anl_roi and stk_anl_roi_event with CW_DEFROI.PRO
;	New routine is shipped with IDL and is more robust on multiple platforms
;	Allow selection of regions of interest as polygon, single point, rectangle, or circle
;
; Changed the way the color table is specified:
;	- calls ZSTACK_COLOR.PRO from within zstack_save_prep
;	- much simpler now, only executed once, allows multiple colors easily
;
; Deleted unused variables
;	char_ypix,charsize,textregion_nlines,textregion_ypix,
;	i_images_color_index,i0_images_color_index,i0_images_list,i_images_list
;
; Renamed ev to ev_list, and msec to msec_list
;
; Added option for data from Polymer STXM
;	/poly keyword and stxm1_sxm2_sm3_als4_poly5 variable
;	Made stxm1_sxm2_sm3_als4_poly5 part of zstack_common variable
;
; Modified Stack Save dialog window for 3 columns, including a long list of image files
;
; Modified COMMON block structure so that common variables are shared with all zstack routines
;	i.e., zstack_common contains variables used by
;		ZSTACK_ANALYZE.PRO, ZSTACK_READLIST.PRO, ZSTACK_BUILDLIST.PRO, and ZSTACK_ALIGN.PRO
; Common variables are now defined only once in each file (in zstack_save_prep), not repetitively as before.
; Common variables for data are now determined within ZSTACK_BUILDLIST.PRO or ZSTACK_READLIST.PRO:
;	image_stack, filename_list, ev_list, msec_list, filename_display_list
;	This requires that files be read only once, eliminated time-intensive duplicate calls of
;		STXM_READ.PRO or SXM_READ.PRO
;
; Modified zstack_save_par
;	so that they only contain only variables associated with dialog window.
;	All other variables have been moved to zstack_analyze_common
;
; Moved list_filename and shift_filename variables to zstack_common variable
; Added n_files variable to zstack_common variable
; Header with list_filename and shift_filename now wriiten as part of *.spc and *.roi files
;
; Ratio of image to I0 spectrum appears to be useless
;	Previously, some slight variation in image contrast was present
;	but was likely due to the way the percent_image was computed:
;	Former:	percent_image = 100. * image_stack(*,*,i_file) / max(image_stack(*,*,i_file))
;					(via obsolete invmax_image_stack variable)
;		which didn't scale image intensity accurately between 0 and 100
;	Now:		this_image = image_stack(*,*,i_file) / min(image_stack(*,*,i_file))
;			percent_image = 100. * this_image / max(this_image)
;		which forces image intensity to be accurately scaled between 0 and 100
;	So eliminate 'ratio image to i0 spectrum' option
;	Explore possibility of displaying image using log or exp scale, in addition to present linear scale
;
; Modified zstack_save_stack_data procedure to save image stack (*.stk)
;	Saved image stack has a format slightly different from CJJ code since it includes the filename_list
;		so the file structure of the two different file formats makes them incompatible
;
; (05oct00 cgz)
;	Modified dialog widget to include capability to select subregion,
;		better capability to select various formats to save data as image, movie, binary
;	Created zstack_save_common to include variables for saving various image and movie formats
;		Moved zstack_save_par and save_filename_header from zstack_spectra_common
;		Moved dragbox from zstack_align_common to zstack_common
;			so that it can be used in zstack_save to select subregion of interest
;		Modified other zstack procedures to conform
;
; (06oct00 cgz)
;	Added capability to specify a subregion using a dragbox routine
;
; (13oct00 cgz) altered definition of dragbox so that it is now [xleft,xright,ybot,ytop]
;		this makes it consistent with definition of other cursor boxes
;		and eliminates need for min and max testing
;		Changed logic statement from:	IF ((dragbox(2) NE 0) AND (dragbox(3) NE 0)) THEN BEGIN
;							to:	IF ((dragbox(1) NE 0) AND (dragbox(3) NE 0)) THEN BEGIN
; (06nov00 cgz)
;	Added button to invoke IDL Slicer with full (unclipped) aligned image stack
; (28nov00 cgz) migrated zstack_profile_colorbar routine to zstack_analyze.pro
; ===============================================================================
; (22feb02 aph) replace cgz modified code with write_sb call for binary stack
; -------- DONE in the zstack_jan01 version (axis_dev)
; (11-jul-04 aph) try to get save images panel to work correctly
;	- mpeg and mgif do not work un der IDL 6.0 (license inhibit)
;	- replace write_gif with write_tiff - does not display image; inverted
; --------
; (16jul04 aph) fix 'invalid widget error' - needed to add CONDITIONAL: IF (data_shifted EQ 1)
;			 on zstack_save_par.clipped_image_label sensitive and desensitive lines
;                convert to write sequence of tif files for  movie generation
; (03-Mar-08 MJ) Keyword /SCROLL in widget_base() needs X_SCROLL_SIZE.
;                Use of /SCROLL and /MODAL at the same time not allowed.
; (13-apr-08 aph) turn on pre-set window size (X_Scroll_size, Y_Scroll_size) only for non-Windows OS
; (07-mar-09 aph) added binary_filenmane to zstack_common
; (27-jul-09 aph) external common; print if no code
; (03-Aug-09 aph) change from base-10 to natural log for spectra (Larry Nitler Carnegie)
; (11-Jan-10 aph) changed write_gif procedure to ax_write_gif procedure to work-around
;                 the conflict of the named write_gif_common common block in IDL's write_gif.pro
;                 with that embedded in stack_analyze.sav (CJJ)
; (22-Jul-14 aph) change writejpeg to writejpeg2000 to try to get movies as multi-image writing to work
; (27-Jul-14 aph) change () to [] with specified ranges
;-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_prep

;print,'zstack_save_prep'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

zstack_color

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_desensitive

on_error,2

;print,'zstack_save_desensitive'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

widget_control, zstack_save_par.browse_filename_label, sensitive = 0
widget_control, zstack_save_par.filename_label, sensitive = 0
widget_control, zstack_save_par.browse_directory_label, sensitive = 0
widget_control, zstack_save_par.directory_label, sensitive = 0
widget_control, zstack_save_par.subregion_label, sensitive = 0
widget_control, zstack_save_par.no_subregion_label, sensitive = 0
widget_control, zstack_save_par.dragbox_label, sensitive = 0
widget_control, zstack_save_par.reset_dragbox_label, sensitive = 0
widget_control, zstack_save_par.clipped_data_label, sensitive = 0
widget_control, zstack_save_par.no_clipped_data_label, sensitive = 0
widget_control, zstack_save_par.image_format_JPEG_label, sensitive = 0
widget_control, zstack_save_par.image_format_GIF_label, sensitive = 0
widget_control, zstack_save_par.image_format_TIFF_label, sensitive = 0
widget_control, zstack_save_par.image_format_PNG_label, sensitive = 0
widget_control, zstack_save_par.image_format_Single_Image_label, sensitive = 0
widget_control, zstack_save_par.image_format_Multiple_Image_label, sensitive = 0
widget_control, zstack_save_par.image_format_Spectra_label, sensitive = 0
widget_control, zstack_save_par.image_format_Orientation_label, sensitive = 0
widget_control, zstack_save_par.image_format_Filename_label, sensitive = 0
widget_control, zstack_save_par.image_format_Ev_label, sensitive = 0
widget_control, zstack_save_par.image_format_Scalebar_label, sensitive = 0
widget_control, zstack_save_par.image_format_ROI_label, sensitive = 0
widget_control, zstack_save_par.image_format_Colorbar_label, sensitive = 0
widget_control, zstack_save_par.movie_format_MPEG_label, sensitive = 0
widget_control, zstack_save_par.movie_format_MGIF_label, sensitive = 0
widget_control, zstack_save_par.movie_format_Images_label, sensitive = 0
widget_control, zstack_save_par.movie_format_Spectra_label, sensitive = 0
widget_control, zstack_save_par.movie_format_Orientation_label, sensitive = 0
widget_control, zstack_save_par.movie_format_Filename_label, sensitive = 0
widget_control, zstack_save_par.movie_format_Ev_label, sensitive = 0
widget_control, zstack_save_par.movie_format_Scalebar_label, sensitive = 0
widget_control, zstack_save_par.movie_format_ROI_label, sensitive = 0
widget_control, zstack_save_par.movie_format_Colorbar_label, sensitive = 0
widget_control, zstack_save_par.binary_format_STK_label, sensitive = 0
widget_control, zstack_save_par.binary_format_BIN_label, sensitive = 0
widget_control, zstack_save_par.binary_format_HDF_label, sensitive = 0
widget_control, zstack_save_par.binary_format_header_label, sensitive = 0
widget_control, zstack_save_par.all_save_label, sensitive = 0
widget_control, zstack_save_par.image_label, sensitive = 0
IF (data_shifted EQ 1) AND (n_roi NE 0) THEN BEGIN
	widget_control, zstack_save_par.clipped_image_label, sensitive = 0
ENDIF
widget_control, zstack_save_par.colorbar_label, sensitive = 0
IF (movie_active EQ 0) THEN BEGIN
	widget_control, zstack_save_par.filename_display_list_label, sensitive = 0
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.filename_display_list_label, sensitive = 1
ENDELSE
widget_control, zstack_save_par.prev_image_label, sensitive = 0
widget_control, zstack_save_par.next_image_label, sensitive = 0
widget_control, zstack_save_par.play_movie_label, sensitive = 0
widget_control, zstack_save_par.display_parameters_label, sensitive = 0
widget_control, zstack_save_par.plot_parameters_label, sensitive = 0
widget_control, zstack_save_par.spectrum_label, sensitive = 0
widget_control, zstack_save_par.IDL_Slicer_label, sensitive = 0
widget_control, zstack_save_par.exit_label, sensitive = 0

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_sensitive

on_error,2

;print,'zstack_save_sensitive'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common


widget_control, zstack_save_par.browse_filename_label, sensitive = 1
widget_control, zstack_save_par.filename_label, sensitive = 1
widget_control, zstack_save_par.browse_directory_label, sensitive = 1
widget_control, zstack_save_par.directory_label, sensitive = 1
;widget_control, zstack_save_par.subregion_label, sensitive = 1
;widget_control, zstack_save_par.no_subregion_label, sensitive = 1
;widget_control, zstack_save_par.dragbox_label, sensitive = 1
;widget_control, zstack_save_par.reset_dragbox_label, sensitive = 1
IF ((dragbox(1) NE 0) AND (dragbox(3) NE 0)) THEN BEGIN
	widget_control, zstack_save_par.subregion_label, set_button = 1
	widget_control, zstack_save_par.subregion_label, sensitive = 1
	widget_control, zstack_save_par.no_subregion_label, sensitive = 1
	widget_control, zstack_save_par.dragbox_label, sensitive = 1
	widget_control, zstack_save_par.reset_dragbox_label, sensitive = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.no_subregion_label, set_button = 1
	widget_control, zstack_save_par.subregion_label, sensitive = 0
	widget_control, zstack_save_par.no_subregion_label, sensitive = 0
	widget_control, zstack_save_par.dragbox_label, sensitive = 1
	widget_control, zstack_save_par.reset_dragbox_label, sensitive = 0
ENDELSE
widget_control, zstack_save_par.clipped_data_label, sensitive = 1
widget_control, zstack_save_par.no_clipped_data_label, sensitive = 1
widget_control, zstack_save_par.image_format_JPEG_label, sensitive = 1
widget_control, zstack_save_par.image_format_GIF_label, sensitive = 1
widget_control, zstack_save_par.image_format_TIFF_label, sensitive = 1
widget_control, zstack_save_par.image_format_PNG_label, sensitive = 1
widget_control, zstack_save_par.image_format_Single_Image_label, sensitive = 1
widget_control, zstack_save_par.image_format_Multiple_Image_label, sensitive = 1
widget_control, zstack_save_par.image_format_Spectra_label, sensitive = 1
widget_control, zstack_save_par.image_format_Orientation_label, sensitive = 1
widget_control, zstack_save_par.image_format_Filename_label, sensitive = 1
widget_control, zstack_save_par.image_format_Ev_label, sensitive = 1
widget_control, zstack_save_par.image_format_Scalebar_label, sensitive = 1
widget_control, zstack_save_par.image_format_ROI_label, sensitive = 1
widget_control, zstack_save_par.image_format_Colorbar_label, sensitive = 0	; disabled
widget_control, zstack_save_par.movie_format_MPEG_label, sensitive = 1
widget_control, zstack_save_par.movie_format_MGIF_label, sensitive = 1
widget_control, zstack_save_par.movie_format_Images_label, sensitive = 1
widget_control, zstack_save_par.movie_format_Spectra_label, sensitive = 1
widget_control, zstack_save_par.movie_format_Orientation_label, sensitive = 1
widget_control, zstack_save_par.movie_format_Filename_label, sensitive = 1
widget_control, zstack_save_par.movie_format_Ev_label, sensitive = 1
widget_control, zstack_save_par.movie_format_Scalebar_label, sensitive = 1
widget_control, zstack_save_par.movie_format_ROI_label, sensitive = 1
widget_control, zstack_save_par.movie_format_Colorbar_label, sensitive = 0	; disabled
widget_control, zstack_save_par.binary_format_STK_label, sensitive = 1
widget_control, zstack_save_par.binary_format_BIN_label, sensitive = 1
widget_control, zstack_save_par.binary_format_HDF_label, sensitive = 0	; disabled
widget_control, zstack_save_par.binary_format_header_label, sensitive = 0	; disabled
IF (strlen(save_filename_header) NE 0) THEN BEGIN	; base filename is given
	CASE 1 OF
		( (total(save_image(0:3)) NE 0) AND $ ; may need to add bit for selecting spectra only
				; saving some form of image
				(save_image(n_elements(save_image)-9) + save_image(n_elements(save_image)-7) EQ 1) ) : BEGIN
				; saving only image or spectra
			widget_control, zstack_save_par.all_save_label, sensitive = 1
		END
		( (total(save_image(0:3)) NE 0) AND $
				; saving some form of image
				(save_image(n_elements(save_image)-9) + save_image(n_elements(save_image)-7) EQ 2) AND $
				; saving both image and spectra
				(save_image(n_elements(save_image)-6) NE 0) ) : BEGIN
			widget_control, zstack_save_par.all_save_label, sensitive = 1
		END
		( (total(save_movie(0:3)) NE 0) AND $
				; saving some form of image
				(save_movie(n_elements(save_movie)-9) + save_movie(n_elements(save_movie)-7) EQ 1) ) : BEGIN
				; saving only image or spectra
			widget_control, zstack_save_par.all_save_label, sensitive = 1
		END
		( (total(save_movie(0:2)) NE 0) AND $
				; saving some form of image
				(save_movie(n_elements(save_movie)-9) + save_movie(n_elements(save_movie)-7) EQ 2) AND $
				; saving both image and spectra
				(save_movie(n_elements(save_movie)-6) NE 0) ) : BEGIN
			widget_control, zstack_save_par.all_save_label, sensitive = 1
		END
		(total(save_binary(0:2)) NE 0) : BEGIN
			widget_control, zstack_save_par.all_save_label, sensitive = 1
		END
		ELSE : BEGIN
			widget_control, zstack_save_par.all_save_label, sensitive = 0
		END
	ENDCASE
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.all_save_label, sensitive = 0
ENDELSE
widget_control, zstack_save_par.image_label, sensitive = 1
IF (data_shifted EQ 1) AND (n_roi NE 0) THEN BEGIN
	widget_control, zstack_save_par.clipped_image_label, sensitive = 1
ENDIF
widget_control, zstack_save_par.colorbar_label, sensitive = 1
IF (movie_active EQ 0) THEN BEGIN
	widget_control, zstack_save_par.filename_display_list_label, sensitive = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.filename_display_list_label, sensitive = 1
ENDELSE
widget_control, zstack_save_par.prev_image_label, sensitive = 1
widget_control, zstack_save_par.next_image_label, sensitive = 1
widget_control, zstack_save_par.play_movie_label, sensitive = 1
widget_control, zstack_save_par.display_parameters_label, sensitive = 1
widget_control, zstack_save_par.plot_parameters_label, sensitive = 1
widget_control, zstack_save_par.spectrum_label, sensitive = 1
widget_control, zstack_save_par.IDL_Slicer_label, sensitive = 1
widget_control, zstack_save_par.exit_label, sensitive = 1


return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_imgdisp,i_file

on_error,2

;print,'zstack_save_imgdisp'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

; create image ready for display including regions of interest
zstack_analyze_imgprep,i_file,image
zstack_analyze_bytescale, image, byte_image

; Display image, applying zoom factor
wset,zstack_save_par.image_win
IF (image_zoom GE 1.0) THEN BEGIN
	IF ((image_zoom) EQ fix(image_zoom)) THEN BEGIN
		tv,rebin(byte_image,n_cols*image_zoom,n_rows*image_zoom,/sample),0,0
	ENDIF ELSE BEGIN
		tv,congrid(byte_image,n_cols*image_zoom,n_rows*image_zoom),0,0
	ENDELSE
ENDIF ELSE BEGIN
	IF ( ((1./image_zoom) EQ fix(1./image_zoom)) AND $
			((image_zoom*n_cols) EQ fix(image_zoom*n_cols)) AND $
			((image_zoom*n_rows) EQ fix(image_zoom*n_rows)) ) THEN BEGIN
		tv,rebin(byte_image,n_cols*image_zoom,n_rows*image_zoom,/sample),0,0
	ENDIF ELSE BEGIN
		tv,congrid(byte_image,n_cols*image_zoom,n_rows*image_zoom),0,0
	ENDELSE
ENDELSE

;dragbox = [25,75,25,75]	; trial dragbox
;dragbox = [5,75,25,75]	; trial dragbox


;  Plot dragbox (if it exists) over raw image
IF ((dragbox(1) NE 0) AND (dragbox(3) NE 0)) THEN BEGIN
    ; Determine dimensions of dragbox
	xleft = dragbox(0)>0
	xright = dragbox(1)<n_cols
	ybot = dragbox(2)>0
	ytop = dragbox(3)<n_rows
	px = image_zoom*[xleft, xright, xright, xleft, xleft] ;X points
	py = image_zoom*[ybot, ybot, ytop, ytop, ybot] ;Y values
	plots,px,py,/device,color=dragbox_color_index
ENDIF ELSE BEGIN  ; set dimensions of dragbox to entire image
    xleft = 0
    xright = n_cols
    ybot = 0
    ytop = n_rows
ENDELSE

; Display clipped shifted image
; 	if there is a non-zero shift, i.e., alignment was kept
; 	if shift is discarded, i.e., all zero, don't display clipped_win_image
IF (data_shifted EQ 1) THEN BEGIN
	; Clip edges of image stack where no data is present due to alignment shifts
	byte_image = byte_image(clipbox[0]:clipbox[1],clipbox[2]:clipbox[3])
	wset,zstack_save_par.clipped_image_win
	IF (image_zoom GE 1.0) THEN BEGIN
		IF ((image_zoom) EQ fix(image_zoom)) THEN BEGIN
			tv,rebin(byte_image,n_clipped_cols*image_zoom,n_clipped_rows*image_zoom,/sample),0,0
		ENDIF ELSE BEGIN
			tv,congrid(byte_image,n_clipped_cols*image_zoom,n_clipped_rows*image_zoom),0,0
		ENDELSE
	ENDIF ELSE BEGIN
		IF ( ((1./image_zoom) EQ fix(1./image_zoom)) AND $
				((image_zoom*n_cols) EQ fix(image_zoom*n_cols)) AND $
				((image_zoom*n_rows) EQ fix(image_zoom*n_rows)) ) THEN BEGIN
			tv,rebin(byte_image,n_clipped_cols*image_zoom,n_clipped_rows*image_zoom,/sample),0,0
		ENDIF ELSE BEGIN
			tv,congrid(byte_image,n_clipped_cols*image_zoom,n_clipped_rows*image_zoom),0,0
		ENDELSE
	ENDELSE

	;  Plot dragbox (if it exists) over shifted image
	IF ((dragbox(1) NE 0) AND (dragbox(3) NE 0)) THEN BEGIN
		xleft = dragbox[0] - clipbox[0]
		xright = (dragbox[1] - clipbox[0]) < clipbox[1]
		ybot = dragbox[2] - clipbox[2]
		ytop = (dragbox[3] - clipbox[2]) <clipbox[3]
		px = image_zoom*[xleft, xright, xright, xleft, xleft] ;X points
		py = image_zoom*[ybot, ybot, ytop, ytop, ybot] ;Y values
		plots,px,py,/device,color=dragbox_color_index
	ENDIF

ENDIF

; Image labeling
widget_control, zstack_save_par.filename_display_list_label,$
		set_droplist_select=i_file

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_plotspectrum, i_file

on_error,2

;print,'zstack_save_plotspectrum'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

IF (strupcase(!d.name) NE 'Z') THEN BEGIN
	wset,zstack_save_par.spectrum_win
ENDIF ELSE BEGIN
;	print,'Z save'
ENDELSE
erase

dummy = where(spectrum NE 0,count)	; if no spectra exist, leave window erased
IF (count EQ 0) THEN BEGIN
	return
ENDIF

; Determine range of x-values in plot
IF (x_autoscale EQ 1)	 THEN BEGIN	; autoscale x-axis
	!x.range = [min(ev_list),max(ev_list)]
ENDIF ELSE BEGIN
	!x.range = [plot_x_min, plot_x_max]
ENDELSE
x_index = where(ev_list GE !x.range[0] AND ev_list LE !x.range[1], count)

; Calculate spectra (Single Beam vs Percent Transmittance vs Absorbance)
; Add in offset
; Determine range of y-values in plot
CASE spectrum_display OF	; Single Beam vs Percent Transmittance vs Absorbance
	1 : BEGIN		; plot single beam spectra
		dummy = where(spectrum[0,*] NE 0,count)
		IF (count NE 0) THEN BEGIN	; if i0 spectrum exists
			dummy = where(spectrum[1:14,*] NE 0,count)
			IF (count GT 0) THEN BEGIN	; if both i0 and some i spectra exist
				spectra = spectrum[0:n_roi,*]				; [i0,i1,i2,i3,...]
				IF (spectrum_offset NE 0) THEN BEGIN	; add in offset to spectra
					FOR i=1,n_roi DO BEGIN
						spectra[i,*] = (spectrum_offset * (i)) + spectra[i,*]
					ENDFOR
				ENDIF
				IF (y_autoscale EQ 1) THEN BEGIN	; autoscale y-axis
					!y.range = [min(spectra[0:n_roi,x_index]),max(spectra[0:n_roi,x_index])]
					!y.range[0] = (1.05 * !y.range[0]) < (0.95 * !y.range[0])
					!y.range[1] = (1.05 * !y.range[1]) > (0.95 * !y.range[1])
				ENDIF ELSE BEGIN
					!y.range = [plot_y_min, plot_y_max]
				ENDELSE
				plot,ev_list,spectra,/nodata, $
						xtitle='eV',ytitle='Single Beam Intensity', $
						xtick_get = xticks, ytick_get = yticks, $
						color=plot_axes_color_index, background=plot_bkgd_color_index
				FOR i=0,n_roi DO BEGIN
					oplot,ev_list,spectra[i,*],color=spectra_color_index(i)
				ENDFOR
				IF (spectrum_offset NE 0) THEN BEGIN	; plot offset label
					label = 'Offset = '+strtrim(string(spectrum_offset,format='(f10.2)'),2)
					xyouts,5,5, /device, color=plot_axes_color_index, charthick=1, $
							alignment=0.0,label
				ENDIF
			ENDIF ELSE BEGIN	; if only i0 spectrum exists
				IF (y_autoscale EQ 1) THEN BEGIN	; autoscale y-axis
					!y.range = [min(spectrum[0,*]),max(spectrum[0,*])]
					!y.range[0] = (1.05 * !y.range[0]) < (0.95 * !y.range[0])
					!y.range[1] = (1.05 * !y.range[1]) > (0.95 * !y.range[1])
				ENDIF ELSE BEGIN
					!y.range = [plot_y_min, plot_y_max]
				ENDELSE
				plot,ev_list,spectrum[0,*],/nodata,xtitle='eV',ytitle='I0', $
						xtick_get = xticks, ytick_get = yticks, $
						color=plot_axes_color_index, background=plot_bkgd_color_index
				oplot,ev_list,spectrum[0,*],color=spectra_color_index(0)
			ENDELSE
		ENDIF ELSE BEGIN	; if i0 spectrum does not exist
			spectra = spectrum[1:n_roi,*]				; [i1,i2,i3,...]
			IF (spectrum_offset NE 0) THEN BEGIN	; add in offset to spectra
				FOR i=1,n_roi-1 DO BEGIN
					spectra[i,*] = (spectrum_offset * (i)) + spectra[i,*]
				ENDFOR
			ENDIF
			IF (y_autoscale EQ 1) THEN BEGIN	; autoscale y-axis
				!y.range = [min(spectra[0:n_roi-1,x_index]),max(spectra[0:n_roi-1,x_index])]
				!y.range[0] = (1.05 * !y.range[0]) < (0.95 * !y.range[0])
				!y.range[1] = (1.05 * !y.range[1]) > (0.95 * !y.range[1])
			ENDIF ELSE BEGIN
				!y.range = [plot_y_min, plot_y_max]
			ENDELSE
			plot,ev_list,spectra,/nodata, $
					xtitle='eV',ytitle='Single Beam Intensity', $
					xtick_get = xticks, ytick_get = yticks, $
					color=plot_axes_color_index, background=plot_bkgd_color_index
			FOR i=0,n_roi-1 DO BEGIN
				oplot,ev_list,spectra[i,*],color=spectra_color_index(i+1)
			ENDFOR
			IF (n_roi GT 1) AND (spectrum_offset NE 0) THEN BEGIN	; plot offset label
					label = 'Offset = '+strtrim(string(spectrum_offset,format='(f10.2)'),2)
					xyouts,5,5, /device, color=plot_axes_color_index, charthick=1, $
							alignment=0.0,label
			ENDIF
		ENDELSE
	END

	2 : BEGIN		; plot percent transmittance spectra
		dummy = where(spectrum[0,*] NE 0,count)
		IF (count NE 0) THEN BEGIN	; if i0 spectrum exists
			dummy = where(spectrum[1:14,*] NE 0,count)
			IF (count GT 0) THEN BEGIN	; if both i0 and some i spectra exist
				spectra = fltarr(n_roi,n_files)
				FOR i=1,n_roi DO BEGIN	; calculate percent transmittance spectra
					spectra[i-1,*] = 100.*spectrum[i,*]/spectrum[0,*]	; [i1/i0,i2/i0,i3/i0,...]
				ENDFOR
				IF (spectrum_offset NE 0) THEN BEGIN	; add in offset to spectra
					FOR i=1,n_roi-1 DO BEGIN
						spectra[i,*] = (spectrum_offset * (i)) + spectra[i,*]
					ENDFOR
				ENDIF
				IF (y_autoscale EQ 1) THEN BEGIN	; autoscale y-axis
					!y.range = [min(spectra[0:n_roi-1,x_index]),max(spectra[0:n_roi-1,x_index])]
					!y.range[0] = (1.05 * !y.range[0]) < (0.95 * !y.range[0])
					!y.range[1] = (1.05 * !y.range[1]) > (0.95 * !y.range[1])
				ENDIF ELSE BEGIN
					!y.range = [plot_y_min, plot_y_max]
				ENDELSE
				plot,ev_list,spectra,/nodata, $
						xtitle='eV',ytitle='Percent Tranmittance', $
						xtick_get = xticks, ytick_get = yticks, $
						color=plot_axes_color_index, background=plot_bkgd_color_index
				FOR i=0,n_roi-1 DO BEGIN
					oplot,ev_list,spectra[i,*],color=spectra_color_index(i+1)
				ENDFOR
				IF (spectrum_offset NE 0) THEN BEGIN	; plot offset label
					label = 'Offset = '+strtrim(string(spectrum_offset,format='(f10.2)'),2)
					xyouts,5,5, /device, color=plot_axes_color_index, charthick=1, $
							alignment=0.0,label
				ENDIF
			ENDIF ELSE BEGIN	; if only i0 spectrum exists
				IF (y_autoscale EQ 1) THEN BEGIN	; autoscale y-axis
					!y.range = [min(spectrum[0,x_index]),max(spectrum[0,x_index])]
					!y.range[0] = (1.05 * !y.range[0]) < (0.95 * !y.range[0])
					!y.range[1] = (1.05 * !y.range[1]) > (0.95 * !y.range[1])
				ENDIF ELSE BEGIN
					!y.range = [plot_y_min, plot_y_max]
				ENDELSE
				plot,ev_list,spectrum[0,*],/nodata,xtitle='eV',ytitle='I0', $
						xtick_get = xticks, ytick_get = yticks, $
						color=plot_axes_color_index, background=plot_bkgd_color_index
				oplot,ev_list,spectrum[0,*],color=spectra_color_index(0)
			ENDELSE
		ENDIF ELSE BEGIN	; if i0 spectrum does not exist
			spectra = spectrum[1:n_roi,*]				; [i1,i2,i3,...]
			IF (spectrum_offset NE 0) THEN BEGIN	; add in offset to spectra
				FOR i=1,n_roi-1 DO BEGIN
					spectra[i,*] = (spectrum_offset * (i)) + spectra[i,*]
				ENDFOR
			ENDIF
			IF (y_autoscale EQ 1) THEN BEGIN	; autoscale y-axis
				!y.range = [min(spectra[0:n_roi-1,x_index]),max(spectra[0:n_roi-1,x_index])]
				!y.range[0] = (1.05 * !y.range[0]) < (0.95 * !y.range[0])
				!y.range[1] = (1.05 * !y.range[1]) > (0.95 * !y.range[1])
			ENDIF ELSE BEGIN
				!y.range = [plot_y_min, plot_y_max]
			ENDELSE
			plot,ev_list,spectra,/nodata, $
					xtitle='eV',ytitle='Single Beam Intensity', $
					xtick_get = xticks, ytick_get = yticks, $
					color=plot_axes_color_index, background=plot_bkgd_color_index
			FOR i=0,n_roi-1 DO BEGIN
				oplot,ev_list,spectra[i,*],color=spectra_color_index(i+1)
			ENDFOR
			IF (n_roi GT 1) AND (spectrum_offset NE 0) THEN BEGIN	; plot offset label
					label = 'Offset = '+strtrim(string(spectrum_offset,format='(f10.2)'),2)
					xyouts,5,5, /device, color=plot_axes_color_index, charthick=1, $
							alignment=0.0,label
			ENDIF
		ENDELSE
	END

	3 : BEGIN		; plot absorbance spectra
		dummy = where(spectrum[0,*] NE 0,count)
		IF (count NE 0) THEN BEGIN	; if i0 spectrum exists
			dummy = where(spectrum[1:14,*] NE 0,count)
			IF (count GT 0) THEN BEGIN	; if both i0 and some i spectra exist
				spectra = fltarr(n_roi,n_files)
				FOR i=1,n_roi DO BEGIN	; calculate absorbance spectra - CHANGE to natural log (03-Augh-09 aph)
					spectra[i-1,*] = -alog(spectrum[i,*]/spectrum[0,*])	; [i1/i0,i2/i0,i3/i0,...]
				ENDFOR
				IF (spectrum_offset NE 0) THEN BEGIN	; add in offset to spectra
					FOR i=1,n_roi-1 DO BEGIN
						spectra[i,*] = (spectrum_offset * (i)) + spectra[i,*]
					ENDFOR
				ENDIF
				IF (y_autoscale EQ 1) THEN BEGIN	; autoscale y-axis
					!y.range = [min(spectra[0:n_roi-1,x_index]),max(spectra[0:n_roi-1,x_index])]
					!y.range[0] = (1.05 * !y.range[0]) < (0.95 * !y.range[0])
					!y.range[1] = (1.05 * !y.range[1]) > (0.95 * !y.range[1])
				ENDIF ELSE BEGIN
					!y.range = [plot_y_min, plot_y_max]
				ENDELSE
				plot,ev_list,spectra,/nodata, $
						xtitle='eV',ytitle='Absorbance', $
						xtick_get = xticks, ytick_get = yticks, $
						color=plot_axes_color_index, background=plot_bkgd_color_index
				FOR i=0,n_roi-1 DO BEGIN
					oplot,ev_list,spectra[i,*],color=spectra_color_index(i+1)
				ENDFOR
				IF (spectrum_offset NE 0) THEN BEGIN	; plot offset label
					label = 'Offset = '+strtrim(string(spectrum_offset,format='(f10.2)'),2)
					xyouts,5,5, /device, color=plot_axes_color_index, charthick=1, $
							alignment=0.0,label
				ENDIF
			ENDIF ELSE BEGIN	; if only i0 spectrum exists
				IF (y_autoscale EQ 1) THEN BEGIN	; autoscale y-axis
					!y.range = [min(spectrum[0,x_index]),max(spectrum[0,x_index])]
					!y.range[0] = (1.05 * !y.range[0]) < (0.95 * !y.range[0])
					!y.range[1] = (1.05 * !y.range[1]) > (0.95 * !y.range[1])
				ENDIF ELSE BEGIN
					!y.range = [plot_y_min, plot_y_max]
				ENDELSE
				plot,ev_list,spectrum[0,*],/nodata,xtitle='eV',ytitle='I0', $
						xtick_get = xticks, ytick_get = yticks, $
						color=plot_axes_color_index, background=plot_bkgd_color_index
				oplot,ev_list,spectrum[0,*],color=spectra_color_index(0)
			ENDELSE
		ENDIF ELSE BEGIN	; if i0 spectrum does not exist
			spectra = spectrum[1:n_roi,*]				; [i1,i2,i3,...]
			IF (spectrum_offset NE 0) THEN BEGIN	; add in offset to spectra
				FOR i=1,n_roi-1 DO BEGIN
					spectra[i,*] = (spectrum_offset * (i)) + spectra[i,*]
				ENDFOR
			ENDIF
			IF (y_autoscale EQ 1) THEN BEGIN	; autoscale y-axis
				!y.range = [min(spectra[0:n_roi-1,x_index]),max(spectra[0:n_roi-1,x_index])]
				!y.range[0] = (1.05 * !y.range[0]) < (0.95 * !y.range[0])
				!y.range[1] = (1.05 * !y.range[1]) > (0.95 * !y.range[1])
			ENDIF ELSE BEGIN
				!y.range = [plot_y_min, plot_y_max]
			ENDELSE
			plot,ev_list,spectra,/nodata, $
					xtitle='eV',ytitle='Single Beam Intensity', $
					xtick_get = xticks, ytick_get = yticks, $
					color=plot_axes_color_index, background=plot_bkgd_color_index
			FOR i=0,n_roi-1 DO BEGIN
				oplot,ev_list,spectra[i,*],color=spectra_color_index(i+1)
			ENDFOR
			IF (n_roi GT 1) AND (spectrum_offset NE 0) THEN BEGIN	; plot offset label
					label = 'Offset = '+strtrim(string(spectrum_offset,format='(f10.2)'),2)
					xyouts,5,5, /device, color=plot_axes_color_index, charthick=1, $
							alignment=0.0,label
			ENDIF
		ENDELSE
	END

	ELSE : BEGIN
		print,'spectrum_display not specified'
	END
ENDCASE

!x.range = [min(xticks),max(xticks)]
!y.range = [min(yticks),max(yticks)]

IF (ev_list(i_file) GT !x.range[0]) AND (ev_list(i_file) LT !x.range[1]) THEN BEGIN
	plots,ev_list(i_file)+[0.,0.],!y.crange,color=spectra_cursor_color_index
ENDIF

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_parse_graphic,i,image

on_error,2

;print,'zstack_save_parse_graphic'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

; set extra pixels for text on right side of image
extra_x_pixels = 0

; set extra pixels for text below image
extra_y_pixels = 0
text_pixels = [0,0,0,0]	; position for scale bar and text, x-ray energy, filename, color bar
text_pixels = [-1,-1,-1,-1]	; position for scale bar and text, x-ray energy, filename, color bar
char_ypix = 16	; this is arbitrary but seems to work well, should be an even integer
IF (save_image[n_elements(save_image)-1] EQ 1) THEN BEGIN	; add extra pixels to x for color bar
	extra_y_pixels = extra_y_pixels + fix(char_ypix)
	text_pixels = text_pixels + [1,1,1,1]
ENDIF
IF (save_image[n_elements(save_image)-4] EQ 1) THEN BEGIN	; add extra pixels to y for x-ray energy text
	extra_y_pixels = extra_y_pixels + fix(char_ypix)
	text_pixels = text_pixels + [1,1,0,0]
ENDIF
IF (save_image[n_elements(save_image)-5] EQ 1) THEN BEGIN	; add extra pixels to y for filename text
	extra_y_pixels = extra_y_pixels + fix(char_ypix)
	text_pixels = text_pixels + [1,1,1,0]
ENDIF
IF (save_image[n_elements(save_image)-3] EQ 1) THEN BEGIN	; add extra pixels to y for scale bar
	extra_y_pixels = extra_y_pixels + fix(char_ypix)
	text_pixels = text_pixels + [1,0,0,0]
ENDIF
IF (extra_y_pixels NE 0) THEN BEGIN
	extra_y_pixels = extra_y_pixels + fix(char_ypix)	; needed for buffer above and below text
	text_pixels = fix((0.5 + text_pixels)*char_ypix) > 0
ENDIF

IF (do_edge_clip EQ 0) THEN BEGIN	; don't clip edges of image

	IF ( (save_subregion EQ 1) AND ( (dragbox(1) NE 0) AND (dragbox(3) NE 0) ) ) THEN BEGIN
			; want to save subregion AND dragbox must be non-zero
			; so clip the image to save dragbox region only
		xleft = dragbox(0)>0
		xright = dragbox(1)<(n_cols-1)
		ybot = dragbox(2)>0
		ytop = dragbox(3)<(n_rows-1)
		n_image_cols = 1 + xright - xleft	; number of columns in dragbox
		n_image_rows = 1 + ytop - ybot	; number of rows in dragbox
print,'1 n_image_cols,n_image_rows : ',n_image_cols,n_image_rows
		; reduce size of image to the dragbox area,  CGZ
		image = image[xleft:xright,ybot:ytop]
	ENDIF ELSE BEGIN
			; want to save full image
		n_image_cols = n_cols
		n_image_rows = n_rows
print,'2 n_image_cols,n_image_rows : ',n_image_cols,n_image_rows
	ENDELSE

ENDIF ELSE BEGIN	; clip edges of data lost due to alignment process

	IF ( (save_subregion EQ 1) AND ( (dragbox(2) NE 0) AND (dragbox(3) NE 0) ) ) THEN BEGIN
			; want to save subregion bounded by both subregion and clipped region
			; so clip the image to save region defined by edges of dragbox and clipbox
		xleft = dragbox(0)>clipbox(0)
		xright = dragbox(1)<clipbox(1)
		ybot = dragbox(2)>clipbox(2)
		ytop = dragbox(3)<clipbox(3)
		n_image_cols = 1 + xright - xleft	; number of columns in dragbox
		n_image_rows = 1 + ytop - ybot	; number of rows in dragbox
print,'3 n_image_cols,n_image_rows : ',n_image_cols,n_image_rows
		; reduce size of image to the dragbox/clipbox area,  CGZ
		image = image[xleft:xright,ybot:ytop]
	ENDIF ELSE BEGIN
			; want to save subregion bounded by clipped region
			; so clip the image to save region defined by edges of clipbox
		xleft = clipbox(0)
		xright = clipbox(1)
		ybot = clipbox(2)
		ytop = clipbox(3)
		n_image_cols = 1 + xright - xleft	; number of columns in dragbox
		n_image_rows = 1 + ytop - ybot	; number of rows in dragbox
print,'4 n_image_cols,n_image_rows : ',n_image_cols,n_image_rows
		; reduce size of image to the clipbox area,  CGZ
		image = image[xleft:xright,ybot:ytop]
	ENDELSE

ENDELSE

device, set_resolution=[n_image_cols*image_zoom,n_image_rows*image_zoom+extra_y_pixels]

IF (image_zoom GE 1.0) THEN BEGIN
	IF ((image_zoom) EQ fix(image_zoom)) THEN BEGIN
		tv,rebin(image,n_image_cols*image_zoom,n_image_rows*image_zoom,/sample),0,extra_y_pixels
	ENDIF ELSE BEGIN
		tv,congrid(image,n_image_cols*image_zoom,n_image_rows*image_zoom),0,extra_y_pixels
	ENDELSE
ENDIF ELSE BEGIN
	IF ( ((1./image_zoom) EQ fix(1./image_zoom)) AND $
			((image_zoom*n_image_cols) EQ fix(image_zoom*n_image_cols)) AND $
			((image_zoom*n_image_rows) EQ fix(image_zoom*n_image_rows)) ) THEN BEGIN
		tv,rebin(image,n_image_cols*image_zoom,n_image_rows*image_zoom,/sample),0,extra_y_pixels
	ENDIF ELSE BEGIN
		tv,congrid(image,n_image_cols*image_zoom,n_image_rows*image_zoom),0,extra_y_pixels
	ENDELSE
ENDELSE

IF (save_image[n_elements(save_image)-3] EQ 1) THEN BEGIN
	; create and plot scale bar with text label
	; we have to calculate the scale bar
	bar_microns = 0.25*abs(x_stop-x_start)
	IF (bar_microns GE 10.) THEN BEGIN
		bar_microns = 10.*fix(0.5+0.1*fix(0.5+bar_microns))
		bar_string = strtrim(string(fix(0.01+bar_microns)),2)+' microns'
	ENDIF ELSE IF (bar_microns GE 1.) THEN BEGIN
		bar_microns = float(fix(0.5+bar_microns))
		IF (bar_microns EQ 1.) THEN BEGIN
			bar_string = '1 micron'
		ENDIF ELSE BEGIN
			bar_string = strtrim(string(fix(0.01+bar_microns)),2)+' microns'
		ENDELSE
	ENDIF ELSE BEGIN
		bar_microns = (0.1*fix(0.5+10*bar_microns))>0.1
		bar_string = strtrim(string(bar_microns,format='(f10.1)'),2)+' microns'
	ENDELSE
	bar_pixels = fix(0.5+float(n_cols)*float(bar_microns) / $
                 float(abs(x_stop-x_start))) > 1
	bar = bytarr(image_zoom*bar_pixels,$
			fix(0.6*char_ypix))+plot_axes_color_index
	; output scale bar with dimension text
;	tv,bar,5,fix(2.5*char_ypix), /device
;	xyouts,(9+bar_pixels*image_zoom),fix(2.5*char_ypix), /device, bar_string, $
;			color=plot_axes_color_index
	tv,bar,5,text_pixels[0], /device
	xyouts,(9+bar_pixels*image_zoom),text_pixels[0], /device, bar_string, $
			color=plot_axes_color_index
ENDIF

; there are some issues with size of the scale bar
; when the saved image (i.e. a subregion) is smaller than the scale bar,
;	there is an error on the tv,bar line.
;	Need to sense size of image so that the scale bar can be resized

IF (save_image[n_elements(save_image)-4] EQ 1) THEN BEGIN
	; output x-ray energy text
	ev_text = strtrim(string(ev_list(i),format='(f10.2)'),2)+' eV'
	xyouts,5,text_pixels[1], /device, ev_text, color=plot_axes_color_index
ENDIF

IF (save_image[n_elements(save_image)-5] EQ 1) THEN BEGIN
	; output filename text
	filename_text = filename_list(i)
	xyouts,5,text_pixels[2], /device, filename_text, color=plot_axes_color_index
ENDIF

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_parse_spectra_graphic,i_spec

on_error,2

;print,'zstack_save_parse_spectra_graphic'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

image2D = tvrd()
erase

;device,set_resolution=[400,300]
device,set_resolution=[(((3*n_cols*image_zoom+25)>250)<500),(((n_rows*image_zoom)>150)<250)]

zstack_save_plotspectrum, i_spec

spec2D = tvrd()
erase
device, /close

svec = [ (size(image2D))[1],(size(image2D))[2],(size(spec2D))[1],(size(spec2D))[2] ]

CASE save_image(n_elements(save_image)-6) OF
	1 : BEGIN	; images left of spectra
		svec(2) = svec(0) + svec(2)
		svec(3) = svec(1) > svec(3)
	END
	2 : BEGIN	; spectra left of images
		svec(2) = svec(0) + svec(2)
		svec(3) = svec(1) > svec(3)
	END
	3 : BEGIN	; images above spectra
		svec(2) = svec(0) > svec(2)
		svec(3) = svec(1) + svec(3)
	END
	4 : BEGIN	; spectra above images
		svec(2) = svec(0) > svec(2)
		svec(3) = svec(1) + svec(3)
	END
	ELSE : BEGIN
		return	; do nothing
	END
ENDCASE

set_plot,'z',/copy
device, set_resolution=[svec(2),svec(3)]

CASE save_image(n_elements(save_image)-6) OF
	1 : BEGIN	; images left of spectra
		tv,image2D,0,fix(0.5*(svec(3) - svec(1)))>0
		tv,spec2D,svec(0),0
	END
	2 : BEGIN	; spectra left of images
		tv,image2D,fix(svec(2) - svec(0)-1)>0,fix(0.5*(svec(3) - svec(1)))>0
		tv,spec2D,0,0
	END
	3 : BEGIN	; images above spectra
		tv,image2D,fix(0.5*(svec(2) - svec(0)))>0,fix(svec(3) - svec(1)-1)>0
		tv,spec2D,0,0
	END
	4 : BEGIN	; spectra above images
		tv,image2D,fix(0.5*(svec(2) - svec(0)))>0,0
		tv,spec2D,0,svec(1)
	END
	ELSE : BEGIN
		return	; do nothing
	END
ENDCASE


return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_roi

on_error,2

;print,'zstack_save_roi'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

print,'zstack_save_roi not implemented yet'
return

length_i0_roi = n_elements(i0_roi)
IF (n_elements(roi_index) GT 1) THEN BEGIN
	length_i_roi = max( roi_index(1:n_elements(roi_index)-1) - roi_index(0:n_elements(roi_index)-2))
ENDIF ELSE BEGIN
	length_i_roi = 0
ENDELSE

; create roi array with io_roi in first column, followed by successive i_roi
;	unused indices are set to -1
roi = intarr(1 + n_roi,1 + max([length_i_roi, length_i0_roi]))
roi[*,*] = -1
roi[0,0] = 0
IF ((size(i0_roi))(0) NE 0) THEN BEGIN
	roi[0,1:length_i0_roi] = i0_roi
ENDIF ELSE BEGIN
	IF (i0_roi NE 0) THEN roi[0,1] = i0_roi
ENDELSE
FOR i=1,n_roi DO BEGIN
	roi[i,0] = i
	dummy = i_roi[roi_index(i-1):(roi_index(i)-1)]		; extract ith set of roi indices
	roi[i,1:n_elements(dummy)] = dummy
ENDFOR

; append length numbers to front of roi array
dummy = intarr(1,1 + max([length_i_roi, length_i0_roi]))
dummy[0,0] = -1
FOR i=1,max([length_i_roi, length_i0_roi]) DO BEGIN
	dummy[0,i] = i
ENDFOR
roi = [dummy,temporary(roi)]

;	output roi indices in columns corresponding to i0, i1, i2, etc.
;	unused indices are set to -1
roi_header = '! Regions of Interest for Spectra'
IF (strlen(strtrim(list_filename,2)) NE 0) THEN BEGIN
	roi_header = roi_header+' : '+list_filename
ENDIF
IF (strlen(strtrim(shift_filename,2)) NE 0) THEN BEGIN
	roi_header = roi_header+' : '+shift_filename
ENDIF
roi_header = roi_header+' !'

openw,lun,roi_filename,/get_lun
printf,lun,roi_header
printf,lun,'PLOTIT('+strtrim(string(max([length_i_roi, length_i0_roi])),2)
printf,lun,roi,format='('+string(n_roi+1)+'(i7,","),i7)'
close,lun
free_lun,lun
print,'Wrote ROI to file "'+data_directory+roi_filename+'"'

return
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_gif, filename

on_error,2

;print,'zstack_save_gif'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

; check if IDL version allows writing gif files
if !version.release GT 5.6 then begin
	print, 'IDL verson 6.0 and above does not support GIF format'
	return
endif


; set_plot,'z' approach does work, reproduces colors well
old_plot=!d.name
set_plot,'z',/copy
erase

; if ROI's are not to be saved with image, temporarily set i_roi and i0_roi to zero
IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
	dummy_i = i_roi
	dummy_i0 = i0_roi
	i_roi = 0
	i0_roi = 0
ENDIF

; create byte-scaled image
zstack_analyze_imgprep,displayed_file_index,byte_image

; parse byte-scaled image with legend text
zstack_save_parse_graphic,displayed_file_index,byte_image

; parse spectra plot
IF (save_image[n_elements(save_image)-7] EQ 1) THEN BEGIN
	zstack_save_parse_spectra_graphic,displayed_file_index
ENDIF

; output as a GIF-formatted graphic
image2D = tvrd()
tvlct,r,g,b,/get
ax_write_gif,filename,image2D,r,g,b
print,'Saved image, '+filename_list(displayed_file_index)+', as '+data_directory+filename
erase
device,/close
set_plot,old_plot

; if ROI's are not to be saved with image, restore i_roi and i0_roi
IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
	i_roi = dummy_i
	i0_roi = dummy_i0
	dummy_i = 0
	dummy_i0 = 0
ENDIF

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_jpeg, filename

on_error,2

;print,'zstack_save_jpeg'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

; set_plot,'z' approach does work, reproduces colors well
old_plot=!d.name
set_plot,'z',/copy
erase

; if ROI's are not to be saved with image, temporarily set i_roi and i0_roi to zero
IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
	dummy_i = i_roi
	dummy_i0 = i0_roi
	i_roi = 0
	i0_roi = 0
ENDIF

; create byte-scaled image
zstack_analyze_imgprep,displayed_file_index,byte_image

; parse byte-scaled image with legend text
zstack_save_parse_graphic,displayed_file_index,byte_image

; parse spectra plot
IF (save_image[n_elements(save_image)-7] EQ 1) THEN BEGIN
	zstack_save_parse_spectra_graphic,displayed_file_index
ENDIF

; output as a JPEG-formatted graphic
image2D = tvrd()
tvlct,r,g,b,/get

; create 3D array for three-color image
s = size(image2D)
image3D = bytarr(3,s(1),s(2))
image3D(0,*,*) = r(image2D)
image3D(1,*,*) = g(image2D)
image3D(2,*,*) = b(image2D)

write_jpeg,filename,image3D, true=1, quality=100
print,'Saved image, '+filename_list(displayed_file_index)+', as '+data_directory+filename
erase
device,/close
set_plot,old_plot

; if ROI's are not to be saved with image, restore i_roi and i0_roi
IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
	i_roi = dummy_i
	i0_roi = dummy_i0
	dummy_i = 0
	dummy_i0 = 0
ENDIF

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_tiff, filename

on_error,2

;print,'zstack_save_tiff'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

; set_plot,'z' approach does work, reproduces colors well
old_plot=!d.name
set_plot,'z',/copy
erase

; if ROI's are not to be saved with image, temporarily set i_roi and i0_roi to zero
IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
	dummy_i = i_roi
	dummy_i0 = i0_roi
	i_roi = 0
	i0_roi = 0
ENDIF

; create byte-scaled image
zstack_analyze_imgprep,displayed_file_index,byte_image

; parse byte-scaled image with legend text
zstack_save_parse_graphic,displayed_file_index,byte_image

; parse spectra plot
IF (save_image[n_elements(save_image)-7] EQ 1) THEN BEGIN
	zstack_save_parse_spectra_graphic,displayed_file_index
ENDIF

; output as a TIFF-formatted graphic
image2D = tvrd()
image2D = reverse(image2D,2)	; needed to flip image about horizontal axis, i.e., top row to bottom row
tvlct,r,g,b,/get
write_tiff,filename,image2D,1,red=r,green=g,blue=b
print,'Saved image, '+filename_list(displayed_file_index)+', as '+data_directory+filename
erase
device,/close
set_plot,old_plot

; if ROI's are not to be saved with image, restore i_roi and i0_roi
IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
	i_roi = dummy_i
	i0_roi = dummy_i0
	dummy_i = 0
	dummy_i0 = 0
ENDIF

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_png, filename

on_error,2

;print,'zstack_save_tiff'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

; set_plot,'z' approach does work, reproduces colors well
old_plot=!d.name
set_plot,'z',/copy
erase

; if ROI's are not to be saved with image, temporarily set i_roi and i0_roi to zero
IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
	dummy_i = i_roi
	dummy_i0 = i0_roi
	i_roi = 0
	i0_roi = 0
ENDIF

; create byte-scaled image
zstack_analyze_imgprep,displayed_file_index,byte_image

; parse byte-scaled image with legend text
zstack_save_parse_graphic,displayed_file_index,byte_image

; parse spectra plot
IF (save_image[n_elements(save_image)-7] EQ 1) THEN BEGIN
	zstack_save_parse_spectra_graphic,displayed_file_index
ENDIF

; output as a PNG-formatted graphic
image2D = tvrd()
image2D = reverse(image2D,2)	; needed to flip image about horizontal axis, i.e., top row to bottom row
tvlct,r,g,b,/get
write_png,filename,image2D,r,g,b
print,'Saved image, '+filename_list(displayed_file_index)+', as '+data_directory+filename

erase
device,/close
set_plot,old_plot

; if ROI's are not to be saved with image, restore i_roi and i0_roi
IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
	i_roi = dummy_i
	i0_roi = dummy_i0
	dummy_i = 0
	dummy_i0 = 0
ENDIF

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_mgif, filename

on_error,2

;print,'zstack_save_mgif'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

; check if IDL version allows writing gif files
if !version.release GT 5.6 then begin
	print, 'IDL verson 6.0 and above does not support MGIF format'
	return
endif

old_plot=!d.name
set_plot,'z',/copy
erase
; temporarily set save_image to save_movie so that zstack_save_parse_graphic will work
temp = save_image
save_image = save_movie

FOR i_file=0,(n_files-1) DO BEGIN
	erase		; erase current z-buffer
	print,'  Writing movie frame '+string(i_file+1,format='(i3)')+$
			' of '+string(n_files,format='(i3)')

	; if ROI's are not to be saved with images, temporarily set i_roi and i0_roi to zero
	IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
		dummy_i = i_roi
		dummy_i0 = i0_roi
		i_roi = 0
		i0_roi = 0
	ENDIF

	; create byte-scaled image
	zstack_analyze_imgprep,i_file,byte_image
	; parse byte-scaled image with legend text
	zstack_save_parse_graphic,i_file,byte_image

	; if ROI's are not to be saved with images, restore i_roi and i0_roi
	IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
		i_roi = dummy_i
		i0_roi = dummy_i0
		dummy_i = 0
		dummy_i0 = 0
	ENDIF

	; parse spectra plot
	IF (save_movie[n_elements(save_movie)-7] EQ 1) THEN BEGIN
		zstack_save_parse_spectra_graphic,i_file
	ENDIF

	; get image from z-buffer and RGB color arrays
	image2D = tvrd()
	tvlct,r,g,b,/get
	; output as a MGIF-formatted graphic
	ax_write_gif,filename,image2D,r,g,b,/multiple
ENDFOR
print,'mgif svec : ',size(image2D)

ax_write_gif,filename,byte_image,/close
print,'Saved GIF movie "'+data_directory+filename+'"'

device,/close
set_plot,old_plot

zstack_save_imgdisp, displayed_file_index
zstack_save_plotspectrum, displayed_file_index

; restore save_image values
save_image = temp

; if ROI's are not to be saved, restore i_roi and i0_roi
IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
	i_roi = dummy_i
	i0_roi = dummy_i0
	dummy_i = 0
	dummy_i0 = 0
ENDIF

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_mpeg2, filename

on_error,2

;print,'zstack_save_mpeg'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

old_plot=!d.name
set_plot,'z',/copy
erase
; temporarily set save_image to save_movie so that zstack_save_parse_graphic will work
temp = save_image
save_image = save_movie

openw,lun,filename,/get_lun

FOR i_file=0,(n_files-1) DO BEGIN
	erase		; erase current z-buffer
	print,'  Writing movie frame '+string(i_file+1,format='(i3)')+$
			' of '+string(n_files,format='(i3)')

	; if ROI's are not to be saved with images, temporarily set i_roi and i0_roi to zero
	IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
		dummy_i = i_roi
		dummy_i0 = i0_roi
		i_roi = 0
		i0_roi = 0
	ENDIF

	; create byte-scaled image
	zstack_analyze_imgprep,i_file,byte_image
	; parse byte-scaled image with legend text
	zstack_save_parse_graphic,i_file,byte_image

	; if ROI's are not to be saved with images, restore i_roi and i0_roi
	IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
		i_roi = dummy_i
		i0_roi = dummy_i0
		dummy_i = 0
		dummy_i0 = 0
	ENDIF

	; parse spectra plot
	IF (save_movie[n_elements(save_movie)-7] EQ 1) THEN BEGIN
		zstack_save_parse_spectra_graphic,i_file
	ENDIF

	; get image from z-buffer and RGB color arrays
	image2D = tvrd()
	tvlct,r,g,b,/get
;print,'!d.x_size,!d.y_size : ',!d.x_size,!d.y_size
	; create 3D array for three-color JPEG image
	s = size(image2D)
	image3D = bytarr(3,s(1),s(2))
	image3D(0,*,*) = r(image2D)
	image3D(1,*,*) = g(image2D)
	image3D(2,*,*) = b(image2D)
	; output as a MPEG-formatted graphic
	write_jpeg2000,image3D, true=1, quality=100, unit=lun		; changed from write_jpeg to write_Jpeg2000
ENDFOR

close,lun

print,'Saved MPEG movie "'+data_directory+filename+'"'

device,/close
set_plot,old_plot

zstack_save_imgdisp, displayed_file_index
zstack_save_plotspectrum, displayed_file_index

; restore save_image values
save_image = temp

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_mpeg1, filename

on_error,2

;print,'zstack_save_mpeg'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

old_plot=!d.name
set_plot,'z',/copy
erase
; temporarily set save_image to save_movie so that zstack_save_parse_graphic will work
temp = save_image
save_image = save_movie

; must display first image with labels and spectra to get size for mpeg
; create byte-scaled image
zstack_analyze_imgprep,displayed_file_index,byte_image
; parse byte-scaled image with legend text
zstack_save_parse_graphic,displayed_file_index,byte_image
; parse spectra plot
IF (save_movie[n_elements(save_movie)-7] EQ 1) THEN BEGIN
	zstack_save_parse_spectra_graphic,displayed_file_index
ENDIF

; get image from z-buffer and size of that image
image2D = tvrd()
svec = size(image2D)

mpegID = mpeg_open([svec(1),svec(2)], filename=filename)	;Open an MPEG sequence with size of z-buffer image

FOR i_file=0,(n_files-1) DO BEGIN
	erase		; erase current z-buffer
	print,'  Writing movie frame '+string(i_file+1,format='(i3)')+$
			' of '+string(n_files,format='(i3)')

	; if ROI's are not to be saved with images, temporarily set i_roi and i0_roi to zero
	IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
		dummy_i = i_roi
		dummy_i0 = i0_roi
		i_roi = 0
		i0_roi = 0
	ENDIF

	; create byte-scaled image
	zstack_analyze_imgprep,i_file,byte_image
	; parse byte-scaled image with legend text
	zstack_save_parse_graphic,i_file,byte_image

	; if ROI's are not to be saved with images, restore i_roi and i0_roi
	IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
		i_roi = dummy_i
		i0_roi = dummy_i0
		dummy_i = 0
		dummy_i0 = 0
	ENDIF

	; parse spectra plot
	IF (save_movie[n_elements(save_movie)-7] EQ 1) THEN BEGIN
		zstack_save_parse_spectra_graphic,i_file
	ENDIF

	; get image from z-buffer and RGB color arrays
	image2D = tvrd()
	tvlct,r,g,b,/get

	; create 3D array for three-color JPEG image
	s = size(image2D)
	image3D = bytarr(3,s(1),s(2))
	image3D(0,*,*) = r(image2D)
	image3D(1,*,*) = g(image2D)
	image3D(2,*,*) = b(image2D)
	; output as a MPEG-formatted graphic
	mpeg_put, mpegID, image=image3D, frame=i_file, /order
ENDFOR

print,'Saving MPEG movie...'
mpeg_save, mpegID
;Save the MPEG sequence in the file myMovie.mpg.
mpeg_close, mpegID	;Close the MPEG sequence.

print,'Saved MPEG movie "'+data_directory+filename+'"'

device,/close
set_plot,old_plot

zstack_save_imgdisp, displayed_file_index
zstack_save_plotspectrum, displayed_file_index

; restore save_image values
save_image = temp

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_mpeg, filename

on_error,2

;print,'zstack_save_mpeg'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

old_plot=!d.name
set_plot,'z',/copy
erase
; temporarily set save_image to save_movie so that zstack_save_parse_graphic will work
temp = save_image
save_image = save_movie

; must display first image with labels and spectra to get size for mpeg
; create byte-scaled image
zstack_analyze_imgprep,displayed_file_index,byte_image
; parse byte-scaled image with legend text
zstack_save_parse_graphic,displayed_file_index,byte_image
; parse spectra plot
IF (save_movie[n_elements(save_movie)-7] EQ 1) THEN BEGIN
	zstack_save_parse_spectra_graphic,displayed_file_index
ENDIF

; get image from z-buffer and size of that image
image2D = tvrd()
svec = size(image2D)

mpegID = mpeg_open([1.1*svec(1),1.1*svec(2)])	;Open an MPEG sequence with size of z-buffer image

FOR i_file=0,(n_files-1) DO BEGIN
	erase		; erase current z-buffer
	print,'  Writing movie frame '+string(i_file+1,format='(i3)')+$
			' of '+string(n_files,format='(i3)')

	; if ROI's are not to be saved with images, temporarily set i_roi and i0_roi to zero
	IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
		dummy_i = i_roi
		dummy_i0 = i0_roi
		i_roi = 0
		i0_roi = 0
	ENDIF

	; create byte-scaled image
	zstack_analyze_imgprep,i_file,byte_image
	; parse byte-scaled image with legend text
	zstack_save_parse_graphic,i_file,byte_image

	; if ROI's are not to be saved with images, restore i_roi and i0_roi
	IF (save_image[n_elements(save_image)-2] EQ 0) THEN BEGIN
		i_roi = dummy_i
		i0_roi = dummy_i0
		dummy_i = 0
		dummy_i0 = 0
	ENDIF

	; parse spectra plot
	IF (save_movie[n_elements(save_movie)-7] EQ 1) THEN BEGIN
		zstack_save_parse_spectra_graphic,i_file
	ENDIF

	; get image from z-buffer and RGB color arrays
	image2D = tvrd()
	tvlct,r,g,b,/get

	; create 3D array for three-color JPEG image
	s = size(image2D)
	image3D = bytarr(3,s(1),s(2))
	image3D(0,*,*) = r(image2D)
	image3D(1,*,*) = g(image2D)
	image3D(2,*,*) = b(image2D)
	; output as a MPEG-formatted graphic
	mpeg_put, mpegID, image=image3D, frame=i_file, /order
ENDFOR

print,'Saving MPEG movie...'
mpeg_save, mpegID, filename=filename
;Save the MPEG sequence in the file myMovie.mpg.
mpeg_close, mpegID	;Close the MPEG sequence.

print,'Saved MPEG movie "'+data_directory+filename+'"'

device,/close
set_plot,old_plot

zstack_save_imgdisp, displayed_file_index
zstack_save_plotspectrum, displayed_file_index

; restore save_image values
save_image = temp

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_mtif, filename

on_error,2

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

print,'zstack_save_mtif  - NOT FUNCTIONAL'

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_mng, filename

on_error,2

print,'zstack_save_mng - NOT FUCNTIONAL'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_stk_data, filename

on_error,2

;print,'zstack_save_stk_data'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

IF (do_edge_clip EQ 0) THEN BEGIN	; don't clip edges of image

	IF ( (save_subregion EQ 1) AND ( (dragbox(1) NE 0) AND (dragbox(3) NE 0) ) ) THEN BEGIN
			; want to save subregion AND dragbox must be non-zero
			; so clip the image to save dragbox region only
		xleft = dragbox(0)>0
		xright = dragbox(1)<(n_cols-1)
		ybot = dragbox(2)>0
		ytop = dragbox(3)<(n_rows-1)
		n_image_cols = 1 + xright - xleft	; number of columns in dragbox
		n_image_rows = 1 + ytop - ybot	; number of rows in dragbox
	ENDIF ELSE BEGIN
			; want to save full image
		xleft = 0
		xright = n_cols-1
		ybot = 0
		ytop = n_rows-1
		n_image_cols = n_cols
		n_image_rows = n_rows
	ENDELSE

ENDIF ELSE BEGIN	; clip edges of data lost due to alignment process

	IF ( (save_subregion EQ 1) AND ( (dragbox(2) NE 0) AND (dragbox(3) NE 0) ) ) THEN BEGIN
			; want to save subregion bounded by both subregion and clipped region
			; so clip the image to save region defined by edges of dragbox and clipbox
		xleft = dragbox(0)>clipbox(0)
		xright = dragbox(1)<clipbox(1)
		ybot = dragbox(2)>clipbox(2)
		ytop = dragbox(3)<clipbox(3)
		n_image_cols = 1 + xright - xleft	; number of columns in dragbox
		n_image_rows = 1 + ytop - ybot	; number of rows in dragbox
	ENDIF ELSE BEGIN
			; want to save subregion bounded by clipped region
			; so clip the image to save region defined by edges of clipbox
		xleft = clipbox(0)
		xright = clipbox(1)
		ybot = clipbox(2)
		ytop = clipbox(3)
		n_image_cols = 1 + xright - xleft	; number of columns in dragbox
		n_image_rows = 1 + ytop - ybot	; number of rows in dragbox
	ENDELSE

ENDELSE

temp_image_stack = fltarr(n_cols,n_rows,n_files)

FOR i_file=0,(n_files-1) DO BEGIN

	; create current image
	CASE image_ratio OF
		0 : BEGIN	; if original data is being displayed
			image = image_stack(*,*,i_file)
		END
		1 : BEGIN	; if (image/current image) is being displayed
			image = image_stack(*,*,i_file) / image_stack(*,*,ratio_image_index)
		END
		2 : BEGIN	; if -log(image/current image) is being displayed
			image = -alog(image_stack(*,*,i_file) / image_stack(*,*,ratio_image_index))
		END
		3 : BEGIN	; if (image - current image) is being displayed
			image = image_stack(*,*,i_file) - image_stack(*,*,ratio_image_index)
		END
		4 : BEGIN	; if (image/i0 spectrum) is being displayed
			image = image_stack(*,*,i_file) / spectrum[0,i_file]
		END
		5 : BEGIN	; if -log(image/i0 spectrum) is being displayed
			image = -alog(image_stack(*,*,i_file) / spectrum[0,i_file])
		END
		6 : BEGIN	; if (image - i0 spectrum) is being displayed
			image = image_stack(*,*,i_file) - spectrum[0,i_file]
		END
		7 : BEGIN	; if (stack - reference stack) is being displayed
			print,'Stack normalization is not currently implemented - will display raw data'
			image = image_stack(*,*,i_file)
;			image = image_stack(*,*,i_file) - spectrum[0,i_file]
		END
		ELSE : BEGIN	; if original data is being displayed
			image = image_stack(*,*,i_file)
		END
	ENDCASE

;	image = image[xleft:xright,ybot:ytop]
	temp_image_stack(*,*,i_file) = image

ENDFOR

temp_start = min([x_start,x_stop],max=temp_stop)
x_start=temp_start
x_stop=temp_stop
x_dist=x_start + (x_stop - x_start) * findgen(n_cols) / float(n_cols-1)
temp_start = min([y_start,y_stop],max=temp_stop)
y_start=temp_start
y_stop=temp_stop
y_dist=y_start + (y_stop - y_start) * findgen(n_rows) / float(n_rows-1)

get_lun,lun
on_ioerror,stack_save_stk_data_bailout
openw,lun,stack_data_filename,/xdr
writeu,lun,long(n_image_cols),long(n_image_rows),long(n_files)
;	writeu,lun,filename_list	; commented out to retain compatibility with CJJ code

;	writeu,lun,float(x_dist(clipbox[0]:clipbox[1])),float(y_dist(clipbox[2]:clipbox[3])),float(ev_list),float(msec_list)
;	writeu,lun,float(image_stack(clipbox[0]:clipbox[1],clipbox[2]:clipbox[3],*))
writeu,lun,float(x_dist(xleft:xright)),float(y_dist(ybot:ytop)),float(ev_list),float(msec_list)
writeu,lun,float(image_stack(xleft:xright,ybot:ytop,*))

print,'Wrote clipped stack data file "'+data_directory+stack_data_filename+'"'

stack_save_stk_data_bailout:
print,'end of zstack_save_stk_data'
close,lun
free_lun,lun

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_bin_data, filename

on_error,2

;print,'zstack_save_bin_data'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

IF (do_edge_clip EQ 0) THEN BEGIN	; don't clip edges of image

	IF ( (save_subregion EQ 1) AND ( (dragbox(1) NE 0) AND (dragbox(3) NE 0) ) ) THEN BEGIN
			; want to save subregion AND dragbox must be non-zero
			; so clip the image to save dragbox region only
		xleft = dragbox(0)>0
		xright = dragbox(1)<(n_cols-1)
		ybot = dragbox(2)>0
		ytop = dragbox(3)<(n_rows-1)
		n_image_cols = 1 + xright - xleft	; number of columns in dragbox
		n_image_rows = 1 + ytop - ybot	; number of rows in dragbox
	ENDIF ELSE BEGIN
			; want to save full image
		xleft = 0
		xright = n_cols-1
		ybot = 0
		ytop = n_rows-1
		n_image_cols = n_cols
		n_image_rows = n_rows
	ENDELSE

ENDIF ELSE BEGIN	; clip edges of data lost due to alignment process

	IF ( (save_subregion EQ 1) AND ( (dragbox(2) NE 0) AND (dragbox(3) NE 0) ) ) THEN BEGIN
			; want to save subregion bounded by both subregion and clipped region
			; so clip the image to save region defined by edges of dragbox and clipbox
		xleft = dragbox(0)>clipbox(0)
		xright = dragbox(1)<clipbox(1)
		ybot = dragbox(2)>clipbox(2)
		ytop = dragbox(3)<clipbox(3)
		n_image_cols = 1 + xright - xleft	; number of columns in dragbox
		n_image_rows = 1 + ytop - ybot	; number of rows in dragbox
	ENDIF ELSE BEGIN
			; want to save subregion bounded by clipped region
			; so clip the image to save region defined by edges of clipbox
		xleft = clipbox(0)
		xright = clipbox(1)
		ybot = clipbox(2)
		ytop = clipbox(3)
		n_image_cols = 1 + xright - xleft	; number of columns in dragbox
		n_image_rows = 1 + ytop - ybot	; number of rows in dragbox
	ENDELSE

ENDELSE

temp_image_stack = fltarr(n_image_cols,n_image_rows,n_files)

FOR i_file=0,(n_files-1) DO BEGIN

	; create current image
	CASE image_ratio OF
		0 : BEGIN	; if original data is being displayed
			image = image_stack(*,*,i_file)
		END
		1 : BEGIN	; if (image/current image) is being displayed
			image = image_stack(*,*,i_file) / image_stack(*,*,ratio_image_index)
		END
		2 : BEGIN	; if -log(image/current image) is being displayed
			image = -alog(image_stack(*,*,i_file) / image_stack(*,*,ratio_image_index))
		END
		3 : BEGIN	; if (image - current image) is being displayed
			image = image_stack(*,*,i_file) - image_stack(*,*,ratio_image_index)
		END
		4 : BEGIN	; if (image/i0 spectrum) is being displayed
			image = image_stack(*,*,i_file) / spectrum[0,i_file]
		END
		5 : BEGIN	; if -log(image/i0 spectrum) is being displayed
			image = -alog(image_stack(*,*,i_file) / spectrum[0,i_file])
		END
		6 : BEGIN	; if (image - i0 spectrum) is being displayed
			image = image_stack(*,*,i_file) - spectrum[0,i_file]
		END
		7 : BEGIN	; if (stack - reference stack) is being displayed
			print,'Stack normalization is not currently implemented - will display raw data'
			image = image_stack(*,*,i_file)
;		image = image_stack(*,*,i_file) - spectrum[0,i_file]
		END
		ELSE : BEGIN	; if original data is being displayed
			image = image_stack(*,*,i_file)
		END
	ENDCASE

	image = image[xleft:xright,ybot:ytop]
	temp_image_stack(*,*,i_file) = image

ENDFOR

; write binary file using STACK_WB.PRO (APH 22-feb-02)
image_stack = temp_image_stack
; print, 'DEBUG: image_stack ', size(image_stack)
stack_wb, filename

temp_image_stack = 0	; reset this

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_hdf_data, filename

on_error,2

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

print,'zstack_save_hdf_data - NOT WRITTEN'

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_header, filename

on_error,2

print,'zstack_save_header - NOT WRITTEN'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

return
END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_all

on_error,2

;print,'zstack_save_all'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

; save jpeg images
IF (save_image[0] EQ 1) THEN BEGIN
	IF (save_image[(n_elements(save_image)-9)] EQ 1) THEN BEGIN	; save only current image
		save_filename = save_filename_header+'.jpg'
		zstack_save_jpeg, save_filename
	ENDIF
	IF (save_image[(n_elements(save_image)-8)] EQ 1) THEN BEGIN	; save all images
		FOR i=0,(n_files-1) DO BEGIN
			IF (displayed_file_index LT (n_files-1)) THEN BEGIN
				displayed_file_index = displayed_file_index+1
			ENDIF ELSE BEGIN
				displayed_file_index = 0
			ENDELSE
			zstack_save_imgdisp, displayed_file_index
			IF (strlen(strtrim(i+1,2)) EQ 1) THEN BEGIN
				num = '0'+strtrim(i+1,2)
			ENDIF ELSE BEGIN
				num = strtrim(i+1,2)
			ENDELSE
			save_filename = save_filename_header+'_'+num+'.jpg'
			zstack_save_jpeg, save_filename
		ENDFOR
	ENDIF
ENDIF

; save gif images
IF (save_image[1] EQ 1) THEN BEGIN
	IF (save_image[(n_elements(save_image)-9)] EQ 1) THEN BEGIN	; save only current image
		save_filename = save_filename_header+'.gif'
		zstack_save_gif, save_filename
	ENDIF
	IF (save_image[(n_elements(save_image)-8)] EQ 1) THEN BEGIN	; save all images
		FOR i=0,(n_files-1) DO BEGIN
			IF (displayed_file_index LT (n_files-1)) THEN BEGIN
				displayed_file_index = displayed_file_index+1
			ENDIF ELSE BEGIN
				displayed_file_index = 0
			ENDELSE
			zstack_save_imgdisp, displayed_file_index
			IF (strlen(strtrim(i+1,2)) EQ 1) THEN BEGIN
				num = '0'+strtrim(i+1,2)
			ENDIF ELSE BEGIN
				num = strtrim(i+1,2)
			ENDELSE
			save_filename = save_filename_header+'_'+num+'.gif'
			zstack_save_gif, save_filename
		ENDFOR
	ENDIF
ENDIF

; save tiff images
IF (save_image[2] EQ 1) THEN BEGIN
	IF (save_image[(n_elements(save_image)-9)] EQ 1) THEN BEGIN	; save only current image
		save_filename = save_filename_header+'.tif'	; save only current image
		zstack_save_tiff, save_filename		; save only current image
	ENDIF
	IF (save_image[(n_elements(save_image)-8)] EQ 1) THEN BEGIN	; save all images
		FOR i=0,(n_files-1) DO BEGIN
			IF (displayed_file_index LT (n_files-1)) THEN BEGIN
				displayed_file_index = displayed_file_index+1
			ENDIF ELSE BEGIN
				displayed_file_index = 0
			ENDELSE
			zstack_save_imgdisp, displayed_file_index
			IF (strlen(strtrim(i+1,2)) EQ 1) THEN BEGIN
				num = '0'+strtrim(i+1,2)
			ENDIF ELSE BEGIN
				num = strtrim(i+1,2)
			ENDELSE
			save_filename = save_filename_header+'_'+num+'.tif'
			zstack_save_tiff, save_filename
		ENDFOR
	ENDIF
ENDIF

; save png images
IF (save_image[3] EQ 1) THEN BEGIN
	IF (save_image[(n_elements(save_image)-9)] EQ 1) THEN BEGIN	; save only current image
		save_filename = save_filename_header+'.png'	; save only current image
		zstack_save_png, save_filename		; save only current image
	ENDIF
	IF (save_image[(n_elements(save_image)-8)] EQ 1) THEN BEGIN	; save all images
		FOR i=0,(n_files-1) DO BEGIN
			IF (displayed_file_index LT (n_files-1)) THEN BEGIN
				displayed_file_index = displayed_file_index+1
			ENDIF ELSE BEGIN
				displayed_file_index = 0
			ENDELSE
			zstack_save_imgdisp, displayed_file_index
			IF (strlen(strtrim(i+1,2)) EQ 1) THEN BEGIN
				num = '0'+strtrim(i+1,2)
			ENDIF ELSE BEGIN
				num = strtrim(i+1,2)
			ENDELSE
			save_filename = save_filename_header+'_'+num+'.png'
			zstack_save_png, save_filename
		ENDFOR
	ENDIF
ENDIF

;; save spectra as gif/jpeg/tiff format
;IF (save_image[2] EQ 1) THEN BEGIN
;	IF (save_image[(n_elements(save_image)-7)] EQ 1) THEN BEGIN	; save only current image
;		save_filename = save_filename_header+'.tif'	; save only current image
;		zstack_save_tiff, save_filename		; save only current image
;	ENDIF
;ENDIF

; save mpeg movie
IF (save_movie[0] EQ 1) THEN BEGIN
	save_filename = save_filename_header+'.mpg'
	zstack_save_mpeg, save_filename
ENDIF

; save mgif movie
IF (save_movie[1] EQ 1) THEN BEGIN
	save_filename = save_filename_header+'_m.gif'
	zstack_save_mgif, save_filename
ENDIF

; save *.stk binary data
IF (save_binary[0] EQ 1) THEN BEGIN
	save_filename = save_filename_header+'.stk'
	zstack_save_stk_data, save_filename
ENDIF

; save *.ncb binary data
IF (save_binary[1] EQ 1) THEN BEGIN
	save_filename = save_filename_header+'.ncb'
	zstack_save_bin_data, save_filename
ENDIF

; save *.hdf binary data
IF (save_binary[2] EQ 1) THEN BEGIN
	save_filename = save_filename_header+'.hdf'
	zstack_save_hdf_data, save_filename
ENDIF

; save header for binary data
IF (save_binary[(n_elements(save_binary)-1)] EQ 1) THEN BEGIN
	save_filename = save_filename_header+'.hdr'
	zstack_save_header, save_filename
ENDIF

return
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_event,event

on_error,2

;print,'zstack_savw_event'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

CASE event.id OF

    zstack_save_par.filename_label : BEGIN
        on_ioerror, save_filename_label_oops
        temp_string = ''
        widget_control, zstack_save_par.filename_label,$
          get_value = temp_string
        save_filename_header = strtrim(temp_string(0),2)
        dotpos = strpos(save_filename_header,'.')
        IF (dotpos NE (-1)) THEN BEGIN
            save_filename_header = strmid(save_filename_header,0,dotpos)
        ENDIF

        save_filename_label_oops:
        widget_control, zstack_save_par.filename_label, $
          set_value = ' '+save_filename_header
        zstack_save_sensitive
    END

    zstack_save_par.browse_directory_label : BEGIN
        on_ioerror, browse_directory_label_oops
        cd,current = current_directory
		dummy = dialog_pickfile( /read, /must_exist, $
			path=data_directory, get_path=data_directory, /directory, $
			title='Select desired directory :')
        		; /directory option will display only directories, not individual files
        widget_control, zstack_save_par.directory_label, $
          set_value = ' '+data_directory
        IF (dummy EQ '') THEN data_directory = current_directory
			; sets data_directory to initial directory if CANCEL is chosen during dialog
			; without this, data_directory becomes null string

        browse_directory_label_oops :
        cd,data_directory	; change directory to data_directory, CGZ
        last_char = strmid(data_directory,strlen(data_directory)-1,1)

		CASE strupcase(!version.os_family) OF
			'VMS' : BEGIN
				IF (last_char NE ']') THEN BEGIN
					data_directory = data_directory+']'
				ENDIF
			END
			'WINDOWS' : BEGIN
				IF (last_char NE '\') THEN BEGIN
					data_directory = data_directory+'\'
				ENDIF
			END
			'MACOS' : BEGIN
				IF (last_char NE ':') THEN BEGIN
					data_directory = data_directory+':'
				ENDIF
			END
			'UNIX' : BEGIN
				IF (last_char NE '/') THEN BEGIN
					data_directory = data_directory+'/'
				ENDIF
			END
			ELSE : BEGIN
				print,'Unrecognized operating system'
			END
		ENDCASE

        widget_control, zstack_save_par.directory_label, $
          set_value = ' '+data_directory
    END

    zstack_save_par.directory_label : BEGIN
        temp_string = ''
        widget_control, zstack_save_par.directory_label, $
          get_value = temp_string
        on_ioerror, directory_label_oops
        data_directory = strtrim(temp_string(0),2)
        directory_label_oops :
        last_char = strmid(data_directory,strlen(data_directory)-1,1)

		CASE strupcase(!version.os_family) OF
			'VMS' : BEGIN
				IF (last_char NE ']') THEN BEGIN
					data_directory = data_directory+']'
				ENDIF
			END
			'WINDOWS' : BEGIN
				IF (last_char NE '\') THEN BEGIN
					data_directory = data_directory+'\'
				ENDIF
			END
			'MACOS' : BEGIN
				IF (last_char NE ':') THEN BEGIN
					data_directory = data_directory+':'
				ENDIF
			END
			'UNIX' : BEGIN
				IF (last_char NE '/') THEN BEGIN
					data_directory = data_directory+'/'
				ENDIF
			END
			ELSE : BEGIN
				print,'Unrecognized operating system'
			END
		ENDCASE

        widget_control, zstack_save_par.directory_label, $
          set_value = ' '+data_directory
print,'data_directory : !'+data_directory+'!'
		cd,data_directory	; change directory to data_directory, CGZ
    END

    zstack_save_par.subregion_label : BEGIN
        save_subregion = 1
    END

    zstack_save_par.no_subregion_label : BEGIN
        save_subregion = 0
    END

    zstack_save_par.dragbox_label : BEGIN
	;; Dragbox can be used to define a region of high contrast for alignment
        zstack_save_desensitive

        wset,zstack_save_par.image_win
        ;	xv	2 point vector of x-coordinate for opposite box corners
        ;	yv	2 point vector of y-coordinate for opposite box corners
        xv=[0,0]
        yv=[0,0]
        ;	x0 and y0 give the initial location of lower left corner of  box
        ;	nx and ny give the initial width and height of box
        x0=0
        y0=0
        nx=0
        ny=0
; output instructions for use of box_cursor to Output Log
	print,string(7B)
	print,'To define Region of Interest box:'
	print,'     Left mouse button   :  Move the box by dragging the mouse'
	print,'     Middle mouse button :  Resize the box by dragging the mouse, moving the nearest corner'
	print,'     Right mouse button  :  Exit and save current box dimensions'
	osname = strupcase(strmid(!Version.os, 0, 3))
	CASE osname OF
		'VMS' : BEGIN
			; three button mouse assumed
		END
		'WIN' : BEGIN
			print, "Drag  Left   button near a corner to resize box."
			print, "Drag  Middle button (if exists) to move box."
			print, "click Right button when done."
;			print,'IDL supports the use of mice with up to three buttons.'
;			print,'However, many mice used with Microsoft Windows systems have only two buttons. '
;			print,'Hold down the Control key while pressing the left mouse button to simulate a "middle" mouse button press.'
		END
		'MAC' : BEGIN
			print,'IDL supports the use of mice with up to three buttons. '
			print,'However, the Macintosh mouse has only one button. '
			print,'When pressed, the Macintosh mouse button is interpreted by IDL as the "left" mouse button. '
			print,'Hold down the Option key while pressing the mouse button to simulate a "middle" mouse button press. '
			print,'Hold down the Command key while pressing the mouse button to simulate a "right" mouse button press.'
		END
		'UNIX' : BEGIN
			; three button mouse assumed
		END
		ELSE : BEGIN
			print,'Unrecognized operating system'
		END
	ENDCASE


; ---------------- aph - box_curosr freezes !! (19-apr-01) try same fix as zstack_align
; widget_control, zstack_save_par.image_label, sensitive = 1
    zstack_save_sensitive

    IF strupcase(!version.os_family) EQ 'WINDOWS' THEN BEGIN
        bx_cursor,x0,y0,nx,ny 				; aph inserted 19-apr-01
 	ENDIF ELSE box_cursor,x0,y0,nx,ny

;  calculate xv and yv to flow back into CJJ code,  CGZ
        xv = [x0,x0+nx]
        yv = [y0,y0+ny]

        if ((xv(1) ne 0) and (yv(1) ne 0)) then begin
            dragbox = [xv(0),xv(1),yv(0),yv(1)]/image_zoom
            print,'save dragbox =',string(dragbox,format='(i6)')
        endif

        IF ( (dragbox(1) NE 0) AND (dragbox(3) NE 0) ) THEN BEGIN
            save_subregion = 1
        ENDIF ELSE BEGIN
            save_subregion = 0
        ENDELSE

        zstack_save_imgdisp,displayed_file_index
        zstack_save_sensitive
    END

    zstack_save_par.reset_dragbox_label : BEGIN
        zstack_save_desensitive
        dragbox = [0,0,0,0]
        print,'save dragbox =',string(dragbox,format='(i6)')
        zstack_save_imgdisp,displayed_file_index
        zstack_save_sensitive
    END

    zstack_save_par.clipped_data_label : BEGIN
        do_edge_clip = 1
    END

    zstack_save_par.no_clipped_data_label : BEGIN
        do_edge_clip = 0
    END

    zstack_save_par.save_roi_label : BEGIN
        save_roi = 1
    END

    zstack_save_par.no_save_roi_label : BEGIN
        save_roi = 0
    END

    zstack_save_par.image_format_JPEG_label : BEGIN
        IF (save_image(0) EQ 0) THEN BEGIN
        	save_image(0) = 1
        ENDIF ELSE BEGIN
        	save_image(0) = 0
        ENDELSE
        zstack_save_sensitive
    END


    zstack_save_par.image_format_GIF_label : BEGIN
        IF (save_image(1) EQ 0) THEN BEGIN
        	save_image(1) = 1
        ENDIF ELSE BEGIN
        	save_image(1) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.image_format_TIFF_label : BEGIN
        IF (save_image(2) EQ 0) THEN BEGIN
        	save_image(2) = 1
        ENDIF ELSE BEGIN
        	save_image(2) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.image_format_PNG_label : BEGIN
        IF (save_image(3) EQ 0) THEN BEGIN
        	save_image(3) = 1
        ENDIF ELSE BEGIN
        	save_image(3) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.image_format_Single_Image_label : BEGIN
        IF (save_image(n_elements(save_image)-9) EQ 0) THEN BEGIN
        	save_image(n_elements(save_image)-9) = 1
        	save_image(n_elements(save_image)-8) = 0
		widget_control, zstack_save_par.image_format_Multiple_Image_label, set_button = 0
        ENDIF ELSE BEGIN
        	save_image(n_elements(save_image)-9) = 0
        	save_image(n_elements(save_image)-8) = 1
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.image_format_Multiple_Image_label : BEGIN
        IF (save_image(n_elements(save_image)-8) EQ 0) THEN BEGIN
        	save_image(n_elements(save_image)-8) = 1
        	save_image(n_elements(save_image)-9) = 0
		widget_control, zstack_save_par.image_format_Single_Image_label, set_button = 0
        ENDIF ELSE BEGIN
        	save_image(n_elements(save_image)-8) = 0
        	save_image(n_elements(save_image)-9) = 1
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.image_format_Spectra_label : BEGIN
        IF (save_image(n_elements(save_image)-7) EQ 0) THEN BEGIN
        	save_image(n_elements(save_image)-7) = 1
        ENDIF ELSE BEGIN
        	save_image(n_elements(save_image)-7) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.image_format_Orientation_label : BEGIN
        save_image(n_elements(save_image)-6) = event.index
        zstack_save_sensitive
    END

    zstack_save_par.image_format_Filename_label : BEGIN
        IF (save_image(n_elements(save_image)-5) EQ 0) THEN BEGIN
        	save_image(n_elements(save_image)-5) = 1
        ENDIF ELSE BEGIN
        	save_image(n_elements(save_image)-5) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.image_format_Ev_label : BEGIN
        IF (save_image(n_elements(save_image)-4) EQ 0) THEN BEGIN
        	save_image(n_elements(save_image)-4) = 1
        ENDIF ELSE BEGIN
        	save_image(n_elements(save_image)-4) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.image_format_Scalebar_label : BEGIN
        IF (save_image(n_elements(save_image)-3) EQ 0) THEN BEGIN
        	save_image(n_elements(save_image)-3) = 1
        ENDIF ELSE BEGIN
        	save_image(n_elements(save_image)-3) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.image_format_ROI_label : BEGIN
        IF (save_image(n_elements(save_image)-2) EQ 0) THEN BEGIN
        	save_image(n_elements(save_image)-2) = 1
        ENDIF ELSE BEGIN
        	save_image(n_elements(save_image)-2) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.image_format_Colorbar_label : BEGIN
        IF (save_image(n_elements(save_image)-1) EQ 0) THEN BEGIN
        	save_image(n_elements(save_image)-1) = 1
        ENDIF ELSE BEGIN
        	save_image(n_elements(save_image)-1) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.movie_format_MPEG_label : BEGIN
        IF (save_movie(0) EQ 0) THEN BEGIN
        	save_movie(0) = 1
        ENDIF ELSE BEGIN
        	save_movie(0) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.movie_format_MGIF_label : BEGIN
        IF (save_movie(1) EQ 0) THEN BEGIN
        	save_movie(1) = 1
        ENDIF ELSE BEGIN
        	save_movie(1) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.movie_format_Images_label : BEGIN
        IF (save_movie(n_elements(save_movie)-8) EQ 0) THEN BEGIN
        	save_movie(n_elements(save_movie)-8) = 1
        ENDIF ELSE BEGIN
        	save_movie(n_elements(save_movie)-8) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.movie_format_Spectra_label : BEGIN
        IF (save_movie(n_elements(save_movie)-7) EQ 0) THEN BEGIN
        	save_movie(n_elements(save_movie)-7) = 1
        ENDIF ELSE BEGIN
        	save_movie(n_elements(save_movie)-7) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.movie_format_Orientation_label : BEGIN
        save_movie(n_elements(save_movie)-6) = event.index
        zstack_save_sensitive
    END


    zstack_save_par.movie_format_Filename_label : BEGIN
        IF (save_movie(n_elements(save_movie)-5) EQ 0) THEN BEGIN
        	save_movie(n_elements(save_movie)-5) = 1
        ENDIF ELSE BEGIN
        	save_movie(n_elements(save_movie)-5) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.movie_format_Ev_label : BEGIN
        IF (save_movie(n_elements(save_movie)-4) EQ 0) THEN BEGIN
        	save_movie(n_elements(save_movie)-4) = 1
        ENDIF ELSE BEGIN
        	save_movie(n_elements(save_movie)-4) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.movie_format_Scalebar_label : BEGIN
        IF (save_movie(n_elements(save_movie)-3) EQ 0) THEN BEGIN
        	save_movie(n_elements(save_movie)-3) = 1
        ENDIF ELSE BEGIN
        	save_movie(n_elements(save_movie)-3) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.movie_format_ROI_label : BEGIN
        IF (save_movie(n_elements(save_movie)-2) EQ 0) THEN BEGIN
        	save_movie(n_elements(save_movie)-2) = 1
        ENDIF ELSE BEGIN
        	save_movie(n_elements(save_movie)-2) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.movie_format_Colorbar_label : BEGIN
        IF (save_movie(n_elements(save_movie)-1) EQ 0) THEN BEGIN
        	save_movie(n_elements(save_movie)-1) = 1
        ENDIF ELSE BEGIN
        	save_movie(n_elements(save_movie)-1) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.binary_format_STK_label : BEGIN
        IF (save_binary(0) EQ 0) THEN BEGIN
        	save_binary(0) = 1
        ENDIF ELSE BEGIN
        	save_binary(0) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.binary_format_BIN_label : BEGIN
        IF (save_binary(1) EQ 0) THEN BEGIN
        	save_binary(1) = 1
        ENDIF ELSE BEGIN
        	save_binary(1) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.binary_format_HDF_label : BEGIN
        IF (save_binary(1) EQ 0) THEN BEGIN
        	save_binary(2) = 1
        ENDIF ELSE BEGIN
        	save_binary(2) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.binary_format_header_label : BEGIN
        IF (save_binary(n_elements(save_binary)-1) EQ 0) THEN BEGIN
        	save_binary(n_elements(save_binary)-1) = 1
        ENDIF ELSE BEGIN
        	save_binary(n_elements(save_binary)-1) = 0
        ENDELSE
        zstack_save_sensitive
    END

    zstack_save_par.all_save_label : BEGIN
        zstack_save_desensitive
        widget_control, hourglass=1
        zstack_save_all
        widget_control, hourglass=0
        zstack_save_sensitive
    END

    zstack_save_par.filename_display_list_label : BEGIN
        zstack_save_desensitive
        displayed_file_index = event.index
        zstack_save_imgdisp, displayed_file_index
        zstack_save_plotspectrum, displayed_file_index
        zstack_save_sensitive
    END

	zstack_save_par.prev_image_label : BEGIN
        zstack_save_desensitive
		IF (displayed_file_index GT 0) THEN BEGIN
			displayed_file_index = displayed_file_index-1
		ENDIF ELSE BEGIN
			displayed_file_index = n_files-1
		ENDELSE
		zstack_save_imgdisp,displayed_file_index
        zstack_save_plotspectrum, displayed_file_index
        zstack_save_sensitive
	END

	zstack_save_par.next_image_label : BEGIN
        zstack_save_desensitive
		IF (displayed_file_index LT (n_files-1)) THEN BEGIN
			displayed_file_index = displayed_file_index+1
		ENDIF ELSE BEGIN
			displayed_file_index = 0
		ENDELSE
		zstack_save_imgdisp,displayed_file_index
        zstack_save_plotspectrum, displayed_file_index
        zstack_save_sensitive
	END

    zstack_save_par.play_movie_label : BEGIN
		movie_active = 1
        zstack_save_desensitive
        FOR i=0,(n_files-1) DO BEGIN
		IF (displayed_file_index LT (n_files-1)) THEN BEGIN
			displayed_file_index = displayed_file_index+1
		ENDIF ELSE BEGIN
			displayed_file_index = 0
		ENDELSE
            zstack_save_imgdisp, displayed_file_index
            zstack_save_plotspectrum, displayed_file_index
            wait,movie_delay
        ENDFOR
		movie_active = 0
        zstack_save_sensitive
    END

	zstack_save_par.display_parameters_label : BEGIN
		zstack_save_desensitive
		wshow,zstack_save_par.main_base_win,0
		zstack_display,'save'
        zstack_save_sensitive
	END

	zstack_save_par.plot_parameters_label : BEGIN
		zstack_save_desensitive
		wshow,zstack_save_par.main_base_win,0
		zstack_plot,'save'
        zstack_save_sensitive
	END

    zstack_save_par.spectrum_label : BEGIN
        ;; only act on a down click of the mouse
        IF (event.type EQ 0) THEN BEGIN
	        zstack_save_desensitive
            wset,zstack_save_par.spectrum_win
            this_ev_abs = convert_coord(event.x,event.y,/device,/to_data)
            this_ev = this_ev_abs(0)
            dummy = min(abs(this_ev-ev_list),this_i_ev)
            print,'You clicked at '+$
              strtrim(string(ev_list(this_i_ev),format='(f10.2)'),2)+' eV, '+$
              strtrim(string(12398.52/ev_list(this_i_ev),format='(f10.3)'),2)+' A'
            displayed_file_index = (this_i_ev>0)<(n_files-1)
            widget_control,zstack_save_par.filename_display_list_label,$
              set_list_select=displayed_file_index
            zstack_save_imgdisp, displayed_file_index
            zstack_save_plotspectrum, displayed_file_index
	        zstack_save_sensitive
        ENDIF
    END

	zstack_save_par.IDL_Slicer_label : BEGIN
	        zstack_save_desensitive
		wshow,zstack_save_par.main_base_win,0
;   reduced_data = image_stack[0:n_cols/2,0:n_rows/2,*]
;		slicer3,reduced_data,group=zstack_spectra_par.main_base,/modal
		slicer3,group=zstack_save_par.main_base,/modal
		; restore color table after IDL Slicer is finished
		wshow,zstack_save_par.main_base_win,1
		zstack_color
		; redisplay images and spectra
		zstack_save_imgdisp, displayed_file_index
		zstack_save_plotspectrum, displayed_file_index
	        zstack_save_sensitive

	END

    zstack_save_par.exit_label : BEGIN
		wshow,zstack_spectra_par.main_base_win
		widget_control,zstack_save_par.main_base,/destroy

		IF (image_zoom EQ init_zoom) THEN BEGIN
			zstack_spectra_sensitive
			zstack_spectra_imgdisp, displayed_file_index
			zstack_spectra_plotspectrum, displayed_file_index
		ENDIF ELSE BEGIN
			widget_control, zstack_spectra_par.main_base, /destroy
			zstack_spectra
			zstack_spectra_sensitive
		ENDELSE
    END
	ELSE : BEGIN
		print,'Unrecognized case in zstack_save_event'
	END

ENDCASE

END

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save_dialog, Group_Leader=groupLeader

on_error,2

;print,'zstack_save_dialog'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

; Initialize variables if they have no value
;	needed when running zstack_align_dialog as stand-alone prior to running zstack_align
;	i.e., when programming dialog window
IF (n_elements(n_cols) EQ 0) THEN n_cols = 100
IF (n_elements(n_rows) EQ 0) THEN n_rows = 100
IF (n_elements(image_zoom) EQ 0) THEN image_zoom = 1
IF (n_elements(spectrum) EQ 0) THEN spectrum = fltarr(15,2)
IF (n_elements(data_shifted) EQ 0) then data_shifted = 0


IF (n_tags(zstack_save_par) EQ 0) THEN BEGIN
    zstack_save_par = $
      { zstack_save_par					    , $
		main_base						: 0L, $
		browse_filename_label				: 0L, $
		filename_label					: 0L, $
		browse_directory_label			: 0L, $
		directory_label					: 0L, $
		subregion_label					: 0L, $
		no_subregion_label				: 0L, $
		dragbox_label					: 0L, $
		reset_dragbox_label				: 0L, $
		clipped_data_label				: 0L, $
		no_clipped_data_label				: 0L, $
		save_roi_label					: 0L, $
		no_save_roi_label				: 0L, $
		image_format_JPEG_label			: 0L, $
		image_format_GIF_label			: 0L, $
		image_format_TIFF_label			: 0L, $
		image_format_PNG_label			: 0L, $
		image_format_Single_Image_label		: 0L, $
		image_format_Multiple_Image_label	: 0L, $
		image_format_Spectra_label			: 0L, $
		image_format_Orientation_label		: 0L, $
		image_format_Filename_label		: 0L, $
		image_format_Ev_label				: 0L, $
		image_format_Scalebar_label		: 0L, $
		image_format_ROI_label			: 0L, $
		image_format_Colorbar_label		: 0L, $
		movie_format_MPEG_label			: 0L, $
		movie_format_MGIF_label			: 0L, $
		movie_format_MNG_label			: 0L, $
		movie_format_Images_label			: 0L, $
		movie_format_Spectra_label			: 0L, $
		movie_format_Orientation_label		: 0L, $
		movie_format_Filename_label		: 0L, $
		movie_format_Ev_label				: 0L, $
		movie_format_Scalebar_label		: 0L, $
		movie_format_ROI_label			: 0L, $
		movie_format_Colorbar_label		: 0L, $
		binary_format_STK_label			: 0L, $
		binary_format_BIN_label			: 0L, $
		binary_format_HDF_label			: 0L, $
		binary_format_header_label			: 0L, $
		all_save_label					: 0L, $
		image_label					: 0L, $
		clipped_image_label				: 0L, $
		colorbar_label					: 0L, $
		filename_display_list_label		: 0L, $
		prev_image_label				: 0L, $
		next_image_label				: 0L, $
		play_movie_label				: 0L, $
		display_parameters_label			: 0L, $
		plot_parameters_label				: 0L, $
		spectrum_label					: 0L, $
		IDL_Slicer_label				: 0L, $
		exit_label						: 0L, $
		main_base_win					: 0L, $
		image_win						: 0L, $
		clipped_image_win				: 0L, $
		colorbar_win					: 0L, $
		spectrum_win					: 0L  $
      }
ENDIF
comp_screen_res=GET_SCREEN_SIZE()

; Start of dialog window for saving images, movies, and data stacks
IF N_Elements(groupLeader) EQ 0 THEN BEGIN
	IF !version.os_family EQ 'Windows' then begin
		zstack_save_par.main_base = widget_base(title='ZSTACK Save', /col, /scroll)
	ENDIF else begin
		zstack_save_par.main_base = widget_base(title='ZSTACK Save', /col, /scroll, $
	              X_SCROLL_SIZE=comp_screen_res(0)*.75,Y_SCROLL_SIZE=comp_screen_res(1)*.95 )
	ENDELSE
ENDIF ELSE BEGIN
	zstack_save_par.main_base = widget_base(title='ZSTACK Save', /col, $
			/Modal, Group_Leader=groupLeader )
ENDELSE
;zstack_save_par.main_base = widget_base(title='ZSTACK Save', /column, /scroll )
row1 = widget_base(zstack_save_par.main_base,/row)
col1 = widget_base(row1,/column)
col2 = widget_base(row1,/column)
col3 = widget_base(row1,/column)

base = widget_base(col2,/column,/frame, space=0)

row = widget_base(base,/row)
col = widget_base(row,/col,/align_center)
zstack_save_par.browse_filename_label = widget_button(col,value='Base filename :')
;label = widget_label( col, value = 'Base filename : ',/align_left)
col = widget_base(row,/col,/align_center)
zstack_save_par.filename_label = widget_text(col,/editable,xsize=25)

row = widget_base(base,/row)
col = widget_base(row,/col,/align_center)
zstack_save_par.browse_directory_label = widget_button(col,value='Directory :     ')
;label = widget_label( col, value = 'Directory : ',/align_left)
col = widget_base(row,/col,/align_center)
zstack_save_par.directory_label = widget_text(col,/editable,xsize=45, ysize=3, /wrap)

row = widget_base(base,/row)
;col = widget_base(row,/col)
row = widget_base(row,/row)
label = widget_label(row,value='Save subregion of data ? ',/align_left)
col = widget_base(row,/col)
row = widget_base(col,/row,/exclusive)
zstack_save_par.subregion_label = widget_button( row, value='Yes')
zstack_save_par.no_subregion_label = widget_button( row, value='No')
row = widget_base(col,/row)
zstack_save_par.dragbox_label = $
    widget_button(row, value='Select subregion')
;row = widget_base(col,/row)
zstack_save_par.reset_dragbox_label = $
    widget_button(row, value='Reset  subregion')

row = widget_base(base,/row)
;col = widget_base(row,/col)
row = widget_base(row,/row)
label = widget_label(row,value='Save data after clipping edges ? ',/align_left)
;col = widget_base(row,/col)
row = widget_base(row,/row,/exclusive)
zstack_save_par.clipped_data_label = widget_button( row, value='Yes')
zstack_save_par.no_clipped_data_label = widget_button( row, value='No')

row = widget_base(base,/row)
;col = widget_base(row,/col)
row = widget_base(row,/row)
label = widget_label(row,value='Save Regions of Interest ? ',/align_left)
;col = widget_base(row,/col)
row = widget_base(row,/row,/exclusive)
zstack_save_par.save_roi_label = widget_button( row, value='Yes')
zstack_save_par.no_save_roi_label = widget_button( row, value='No')

row = widget_base(base,/row)
col = widget_base(row,/col)
label = widget_label(col, value = 'Image format : ',/align_left)
col = widget_base(row,/col)
row = widget_base(col,/row,/nonexclusive)
zstack_save_par.image_format_JPEG_label = widget_button( row, value='JPEG')
zstack_save_par.image_format_GIF_label = widget_button( row, value='GIF')
zstack_save_par.image_format_TIFF_label = widget_button( row, value='TIFF')
zstack_save_par.image_format_PNG_label = widget_button( row, value='PNG')
row = widget_base(col,/row,/nonexclusive)
zstack_save_par.image_format_Single_Image_label = widget_button( row, value='Current image')
zstack_save_par.image_format_Multiple_Image_label = widget_button( row, value='All images')
zstack_save_par.image_format_Spectra_label = widget_button( row, value='Spectra')
row = widget_base(col,/row)
dummy = widget_label(row, value='     ')
zstack_save_par.image_format_Orientation_label =  widget_droplist( row, value = ['Orientation', $
					'Images to left of Spectra', 'Spectra to left of Images', $
					'Images over Spectra', 'Spectra over Images'] )
row = widget_base(col,/row,/nonexclusive)
zstack_save_par.image_format_Filename_label = widget_button( row, value='Filename')
zstack_save_par.image_format_Ev_label = widget_button( row, value='X-ray Energy')
zstack_save_par.image_format_Scalebar_label = widget_button( row, value='Scale bar')
row = widget_base(col,/row,/nonexclusive)
zstack_save_par.image_format_ROI_label = widget_button( row, value='Spectral Regions of Interest')
zstack_save_par.image_format_Colorbar_label = widget_button( row, value='Color bar')

row = widget_base(base,/row)
col = widget_base(row,/col)
label = widget_label(col, value = 'Movie format : ',/align_left)
col = widget_base(row,/col)
row = widget_base(col,/row,/nonexclusive)
zstack_save_par.movie_format_MPEG_label = widget_button( row, value='MPEG')
zstack_save_par.movie_format_MGIF_label = widget_button( row, value='MGIF')
row = widget_base(col,/row,/nonexclusive)
zstack_save_par.movie_format_Images_label = widget_button( row, value='Images')
zstack_save_par.movie_format_Spectra_label = widget_button( row, value='Spectra')
row = widget_base(col,/row)
dummy = widget_label(row, value='     ')
zstack_save_par.movie_format_Orientation_label =  widget_droplist( row, value = ['Orientation', $
					'Images to left of Spectra', 'Spectra to left of Images', $
					'Images over Spectra', 'Spectra over Images'] )
row = widget_base(col,/row,/nonexclusive)
zstack_save_par.movie_format_Filename_label = widget_button( row, value='Filenames')
zstack_save_par.movie_format_Ev_label = widget_button( row, value='X-ray Energies')
zstack_save_par.movie_format_Scalebar_label = widget_button( row, value='Scale bar')
row = widget_base(col,/row,/nonexclusive)
zstack_save_par.movie_format_ROI_label = widget_button( row, value='Spectral Regions of Interest')
zstack_save_par.movie_format_Colorbar_label = widget_button( row, value='Color bar')

row = widget_base(base,/row)
col = widget_base(row,/col)
label = widget_label(col, value = 'Binary data format : ',/align_left)
col = widget_base(row,/col)
row = widget_base(col,/row,/nonexclusive)
zstack_save_par.binary_format_STK_label = widget_button( row, value='*.STK')
zstack_save_par.binary_format_BIN_label = widget_button( row, value='*.NCB')
zstack_save_par.binary_format_HDF_label = widget_button( row, value='*.HDF')
row = widget_base(col,/row,/nonexclusive)
zstack_save_par.binary_format_header_label = widget_button( row, value='Header file')

; delete this when all features are implemented zzz
label = widget_label(base, $
	value='NB : Disabled buttons are features that are not fully implemented')

zstack_save_par.all_save_label = widget_button(base,value='Save')


; Right-hand column of dialog window
base = widget_base(col3,/row,/frame,/align_center)
col3a = widget_base(base,/col)
IF (data_shifted EQ 1) THEN BEGIN
	label = widget_label(col3a, value='Shifted Image',/align_center)
ENDIF ELSE BEGIN
	label = widget_label(col3a, value='Unshifted Image',/align_center)
ENDELSE
zstack_save_par.image_label = widget_draw(col3a,$
              xsize=n_cols*image_zoom,$
              ysize=n_rows*image_zoom,$
              retain=2,/button_events,/align_center)

; if there is a non-zero shift, i.e., alignment was kept, display clipped image
; if shift is discarded, i.e., all zero, don't display clipped image
IF (data_shifted EQ 1) THEN BEGIN
	col3b = widget_base(base,/col)
	label = widget_label(col3b, value='Clipped Image',/align_center)
	zstack_save_par.clipped_image_label = widget_draw(col3b,$
			xsize=n_clipped_cols*image_zoom,$
			ysize=n_clipped_rows*image_zoom,$
			retain=2,/button_events,/align_center)
ENDIF

col3c = widget_base(base,/col)
label = widget_label(col3c, value='I',/align_center)
zstack_save_par.colorbar_label = widget_draw(col3c,$
			xsize=10*(image_zoom>1), ysize=n_rows*image_zoom,$
			retain=2, sensitive=0, /align_center)

zstack_save_par.filename_display_list_label = widget_droplist( col3, $
			value = 'Select File', /align_center, /dynamic_resize)
			;, scr_xsize=150, scr_ysize=20)
zstack_save_par.prev_image_label = $
		widget_button(col3, value='Display Previous Image')
zstack_save_par.next_image_label = $
		widget_button(col3, value='Display Next Image')
zstack_save_par.play_movie_label = $
		widget_button(col3,value='Play movie')
row = widget_base( col3, /row ,/align_center)
zstack_save_par.display_parameters_label = widget_button(row,value='Display Parameters')
zstack_save_par.plot_parameters_label = widget_button(row,value=' Plot  Parameters ')


;dummy = where(spectrum NE 0, count)
;IF (count NE 0) THEN BEGIN	; if some spectra exist
	zstack_save_par.spectrum_label = $
		widget_draw(col3,xsize=((3*n_cols*image_zoom+25)>250)<500, $
					ysize=((n_rows*image_zoom)>150)<250,retain=2, $
					/button_events,/align_center)
;ENDIF

row = widget_base(col3,/row)
zstack_save_par.IDL_Slicer_label = widget_button(col3,value='IDL Slicer')
zstack_save_par.exit_label = widget_button(col3,value='Return to ZSTACK Spectra')

;;;;;;;;;;

Device, get_screen_size=screen_size
screen_center = [ screen_size(0) / 2 , screen_size(1) / 2 ]
geom = Widget_Info(zstack_save_par.main_base, /Geometry)
base_size = [geom.scr_xsize,geom.scr_ysize]
x_base_size = (fix(0.90*screen_size[0]) < base_size[0])
y_base_size = (fix(0.95*screen_size[1]) < base_size[1])
halfsize = [ x_base_size / 2 , y_base_size / 2 ]
widget_control, zstack_save_par.main_base, $
	XOffset = screen_center[0] - halfsize[0], $
	YOffset = screen_center[1] - halfsize[1], $
	scr_xsize = x_base_size, $
	scr_ysize = y_base_size

widget_control, zstack_save_par.main_base, /realize

zstack_save_par.main_base_win = !d.window
widget_control,zstack_save_par.image_label,get_value=window
zstack_save_par.image_win = window
IF (data_shifted EQ 1) THEN BEGIN
	widget_control,zstack_save_par.clipped_image_label,get_value=window
	zstack_save_par.clipped_image_win = window
ENDIF
widget_control,zstack_save_par.colorbar_label, get_value = window
zstack_save_par.colorbar_win = window
;dummy = where(spectrum NE 0, count)
;IF (count NE 0) THEN BEGIN	; if some spectra exist
	widget_control,zstack_save_par.spectrum_label,get_value=window
	zstack_save_par.spectrum_win = window
;ENDIF

; make image and plot widgets inactive
widget_control, zstack_save_par.image_label, sensitive = 0
IF (data_shifted EQ 1) THEN BEGIN
	widget_control, zstack_save_par.clipped_image_label, sensitive = 0
ENDIF


return
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

PRO zstack_save, new_zoom=new_zoom, Group_Leader=groupLeader

on_error,2

;print,'zstack_save'

@bsif_common
@zstack_common
@zstack_analyze_common
@zstack_build_list_common
@zstack_align_common
@zstack_tune_common
@zstack_spectra_common
@zstack_profile_common
@zstack_save_common
@zstack_display_common
@zstack_color_common

on_error,2

IF NOT(keyword_set(new_zoom)) THEN BEGIN
	; set initial values of zstack_save variables
save_filename_header = ''
save_subregion = 0
dragbox = [0,0,0,0]	; [xleft,xright,ybot,ytop]

do_edge_clip = 1	;1
save_roi = 0

save_image = [ 	0, $	; save image as JPEG, [0]
			0, $	; save image as GIF, [1]
			0, $	; save image as TIFF, [2]
			0, $	; save image as PNG, [3]
			1, $	; save single image (default), [n_elements-9]
			0, $	; save all images in separate files, [n_elements-8]
			0, $	; save image with spectra, [n_elements-7]
			0, $	; save movie with specified orientation, [n_elements-6]
				;		0	orientation header
				;		1	images left of spectra
				;		2	spectra left of images
				;		3	images above spectra
				;		4	spectra above images
			0, $	; save image with filename, [n_elements-5]
			0, $	; save image with x-ray energy, [n_elements-4]
			0, $	; save image with scalebar, [n_elements-3]
			1, $	; save image with ROI, [n_elements-2]
			0  ]	; save image with color bar, [n_elements-1]

save_movie = [ 	0, $	; save movie as MPEG, [0]
			0, $	; save movie as MGIF, [1]
			0, $	; save movie as MTIFF, [2]
			0, $	; save image as MNG, [3]
			1, $	; save movie with images (default), [n_elements-9]
			0, $	; unused, needed for capatibility with save_image, [n_elements-8]
			0, $	; save movie with spectra, [n_elements-7]
			0, $	; save movie with specified orientation, [n_elements-6]
				;		0	orientation header
				;		1	images left of spectra
				;		2	spectra left of images
				;		3	images above spectra
				;		4	spectra above images
			0, $	; save movie with filename, [n_elements-5]
			0, $	; save movie with x-ray energy, [n_elements-4]
			0, $	; save movie with scalebar, [n_elements-3]
			1, $	; save movie with ROI, [n_elements-2]
			0  ]	; save movie with color bar, [n_elements-1]

save_binary = [	0, $	; save image stack data in *.STK binary format, [0]
			0, $	; save image stack data in *.NCB binary format, [1]
			0, $	; save image stack data in *.HDF binary format, [2]
			0 ]	; save header file for corresponding binary data file, [n_elements-1]

ENDIF

zstack_save_dialog, Group_Leader=groupLeader

; set initial value of save_filename_header if list_filename exists and save_filename_header is not already defined
IF ( (strlen(save_filename_header) EQ 0) AND (strlen(list_filename) NE 0) )THEN BEGIN
	save_filename_header = str_sep(list_filename,'.')
	save_filename_header = save_filename_header(0)
ENDIF

widget_control, zstack_save_par.filename_display_list_label, $
		set_value = filename_display_list
widget_control, zstack_save_par.filename_label, $
		set_value = ' '+save_filename_header
cd,data_directory,current=current_directory
widget_control, zstack_save_par.directory_label, $
		set_value = ' '+data_directory

; since do_edge_clip = 1,  0 for no edge clipping, 1 for edge clipping
IF (do_edge_clip EQ 1) THEN BEGIN
	widget_control, zstack_save_par.clipped_data_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.no_clipped_data_label, set_button = 1
ENDELSE
IF (save_subregion EQ 1) THEN BEGIN
	widget_control, zstack_save_par.subregion_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.no_subregion_label, set_button = 1
ENDELSE
IF (save_roi EQ 1) THEN BEGIN
	widget_control, zstack_save_par.save_roi_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.no_save_roi_label, set_button = 1
ENDELSE

IF (save_image[0] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.image_format_JPEG_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.image_format_JPEG_label, set_button = 0
ENDELSE
IF (save_image[1] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.image_format_GIF_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.image_format_GIF_label, set_button = 0
ENDELSE
IF (save_image[2] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.image_format_TIFF_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.image_format_TIFF_label, set_button = 0
ENDELSE
IF (save_image[n_elements(save_image)-9] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.image_format_Single_Image_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.image_format_Single_Image_label, set_button = 0
ENDELSE
IF (save_image[n_elements(save_image)-8] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.image_format_Multiple_Image_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.image_format_Multiple_Image_label, set_button = 0
ENDELSE
IF (save_image[n_elements(save_image)-7] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.movie_format_Spectra_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.movie_format_Spectra_label, set_button = 0
ENDELSE

IF (save_image[n_elements(save_image)-5] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.image_format_Filename_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.image_format_Filename_label, set_button = 0
ENDELSE
IF (save_image[n_elements(save_image)-4] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.image_format_Ev_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.image_format_Ev_label, set_button = 0
ENDELSE
IF (save_image[n_elements(save_image)-3] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.image_format_Scalebar_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.image_format_Scalebar_label, set_button = 0
ENDELSE
IF (save_image[n_elements(save_image)-2] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.image_format_ROI_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.image_format_ROI_label, set_button = 0
ENDELSE
IF (save_image[n_elements(save_image)-1] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.image_format_Colorbar_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.image_format_Colorbar_label, set_button = 0
ENDELSE


IF (save_movie[0] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.movie_format_MPEG_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.movie_format_MPEG_label, set_button = 0
ENDELSE
IF (save_movie[1] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.movie_format_MGIF_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.movie_format_MGIF_label, set_button = 0
ENDELSE
IF (save_movie[n_elements(save_movie)-9] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.movie_format_Images_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.movie_format_Images_label, set_button = 0
ENDELSE
IF (save_movie[n_elements(save_movie)-7] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.movie_format_Spectra_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.movie_format_Spectra_label, set_button = 0
ENDELSE
; insert case structure to select orientation pulldown menu setting  ???
IF (save_movie[n_elements(save_movie)-5] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.movie_format_Filename_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.movie_format_Filename_label, set_button = 0
ENDELSE
IF (save_image[n_elements(save_image)-4] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.movie_format_Ev_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.movie_format_Ev_label, set_button = 0
ENDELSE
IF (save_movie[n_elements(save_movie)-3] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.movie_format_Scalebar_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.movie_format_Scalebar_label, set_button = 0
ENDELSE
IF (save_image[n_elements(save_image)-2] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.movie_format_ROI_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.movie_format_ROI_label, set_button = 0
ENDELSE
IF (save_movie[n_elements(save_movie)-1] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.movie_format_Colorbar_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.movie_format_Colorbar_label, set_button = 0
ENDELSE


IF (save_binary[0] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.binary_format_STK_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.binary_format_STK_label, set_button = 0
ENDELSE
IF (save_binary[1] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.binary_format_BIN_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.binary_format_BIN_label, set_button = 0
ENDELSE
IF (save_binary[2] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.binary_format_HDF_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.binary_format_HDF_label, set_button = 0
ENDELSE
IF (save_binary[n_elements(save_binary)-1] EQ 1) THEN BEGIN
	widget_control, zstack_save_par.binary_format_header_label, set_button = 1
ENDIF ELSE BEGIN
	widget_control, zstack_save_par.binary_format_header_label, set_button = 0
ENDELSE

zstack_save_sensitive

; print,'Displaying the first image 1'
zstack_save_plotspectrum, displayed_file_index
zstack_save_imgdisp, displayed_file_index
zstack_analyze_colorbar, zstack_save_par.colorbar_win

xmanager, 'zstack_save', zstack_save_par.main_base, $
  group_leader = zstack_save_par.main_base

return
end
