; Copyright (c) 1998-2013 A.P. Hitchcock; A. Smith  All rights reserved
;+
;NAME:
;		TIF_CONVERT
;
;LAST CHANGED: ----------------------------------- 	11-Mar-2013 (aph)
;
; PURPOSE:
;	This file contains a set of procedures which are a widget to
; convert tif files written by various cameras to a set of NetCDF files
; or *.ncb file for use in aXis2000.
; Relative to the text-only approach of ax_peem_rd.pro, this widget
; has provision for graphical selection of the region of interest.
; Adapted to be called from axis2000
;
; CATEGORY:
;	Image conversion.
;
; CALLING SEQUENCE:
; read~images+peem TIF_CONVERT:
;
; PROCEDURES
; tif_convert_prep
; tif_convert_limits_get_prep
; tif_convert_limits_get_imgdisp
; tif_convert_gl_dialogue_event
; tif_convert_gl_dialogue
; tif_convert_limits_get
; tif_convert
;
; INPUTS: none required
;
; KEYWORDS: none
;
; OUTPUTS:
;	*.nc files are written if requested by user
;
; COMMON BLOCKS:
;  @AXIS_COM	standard set of common blocks
;  @BSIF_com
;  @tif_convert_com
;  @limits_get_common
;
; MODIFICATION HISTORY:
; (06-aug-02 aph) AXIS standard header added; integrated with axis2000
; (30-apr-03 aph) adapt for SRC, sphinx data
; (14-may-03 aph) add direct conversion to ncb; move to stack.convert menu; scale in nm/pixel
; (28-jul-03 aph) replaced 'label' names in setting up widget - conflict with Label array in axis.com
; (17-may-04 aph) adapt for Lox stacks
; (04-Jun-04 aph) modify name parsing to get all characters of filename in filename_ev_msec_list
;                make work with sub-sets of the list
; (26-may-05 aph) set up microscope default settings; rationalize parameter display & setting
; (13-jul-05 aph) continue adapting PEEM_general for auto-configure to specific microscopes
;                 reconfigured switches to make value and button the same
;				  preserve values between read-ins (unless close IDL)
; (16-oct-05 aph) change read_lox to read_lox_spectra
; (20-jan-07 aph) add in processing for ALS PEEM-3 format files
; (05-apr-07 aph) correct pix_siz - was calling tif_rdim, rd_peem with scale in nm not microns
;                 so image dimensions were wrong
; (12-Sep-07 aph) add group keyword to all calls ro Read_PEEM3
; (07-Aug-08 aph) add switch to select / de-select I-ring normalization
; (30-jul-09 aph) changed analcom to stack_process_com (update to stack_process) NB not done in initial Sep-08 change
; (11-Mar-13 aph) include processing for SagaLS Elmitec PEEM (energy scale generator)
;-

;-----------------------------------------------------------------


Function peem_normalize, d, scandef, current=current
; --------------- normalize to  ring current to give response as per a pre-defined value(400 mA)
@tif_convert_com
@bsif_com
@axis_com

on_error,2

if norm_flag EQ 0 then begin
	norm_string = ''
	return,d
endif
norm = 400		; default to 400 mA - ultimately put in axis.ini
if not keyword_Set(current) then begin
	test = strupcase(tag_names(scandef))
	q = where(test EQ 'STORAGERINGCURRENT', count)
	if count GT 0 then begin
		Iring= ScanDef.STORAGERINGCURRENT
;		axis_log, 'Ring current (mA) ' + string(Iring, format='(F6.1)')
		d = d*norm/Iring
	endif else axis_log, 'ring current not avilable - not normalized'
endif else d = d*norm/current
norm_string = 'N - 400mA'
RETURN, d
END
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro tif_convert_limits_get_prep
COMMON limits_get_common,	 $
	limits_get_par, gl_image_zoom,	gl_region, org_region, gl_filelist,	$
	i_file, n_file, button_down, sx, sy, 			$
	box_color, box_ID, box_xsize, box_ysize
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PRO tif_convert_limits_get_imgdisp
;
COMMON limits_get_common
@tif_convert_com
@bsif_com
@axis_com
; Display image, applying zoom factor
file_in = gl_filelist(i_file)

CASE microscope OF
	'Lox' 		: tmp = img_load(file=file_in, /lox, /values)
	'Sphinx'	: tmp = rd_peem(file_in, bits12=bits12, energy=1, scale=1)
	'ALS-PEEM2' : tmp = rd_peem(file_in, bits12=bits12, energy=1, scale=1)
	'ALS-PEEM3' : tmp = read_peem3(file=file_in, group=axis_ID)
	'ALS-pre-Sep02' :  tmp = rd_peem(file_in, bits12=bits12, energy=1, scale=1)
	'Saga-LS-Elmitec' : tmp = rd_peem(file_in, bits12=bits12, energy=1, scale=1)
	'Other' 	:  tmp = rd_peem(file_in, bits12=bits12, energy=1, scale=1)
ENDCASE
svec=size(tmp.d)
n_cols = svec[1]
n_rows = svec[2]
display_img = uint(tmp.d)
wset,limits_get_par.image_win
; --------- force color table to grayscale
loadct,0,/silent
IF (gl_image_zoom GE 1.0) THEN BEGIN
	IF ((gl_image_zoom) EQ fix(gl_image_zoom)) THEN BEGIN
		tvscl,rebin(display_img,n_cols*gl_image_zoom,n_rows*gl_image_zoom,/sample),0,0
	ENDIF ELSE BEGIN
		tvscl,congrid(display_img,n_cols*gl_image_zoom,n_rows*gl_image_zoom),0,0
	ENDELSE
ENDIF ELSE BEGIN
	IF ( ((1./gl_image_zoom) EQ fix(1./gl_image_zoom)) AND $
			((gl_image_zoom*n_cols) EQ fix(gl_image_zoom*n_cols)) AND $
			((gl_image_zoom*n_rows) EQ fix(gl_image_zoom*n_rows)) ) THEN BEGIN
		tvscl,rebin(display_img,n_cols*gl_image_zoom,n_rows*gl_image_zoom,/sample),0,0
	ENDIF ELSE BEGIN
		tvscl,congrid(display_img,n_cols*gl_image_zoom,n_rows*gl_image_zoom),0,0
	ENDELSE
ENDELSE
RETURN
END
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro tif_convert_gl_dialogue_event, event
COMMON limits_get_common
on_error, 2
@axis_com
@bsif_com
;
CASE event.id OF
	limits_get_par.image_label : BEGIN
		dummy_x = event.x
		dummy_y = event.y
		xout = dummy_x/gl_image_zoom
		yout = dummy_y/gl_image_zoom
		widget_control, limits_get_par.x_value,set_value=string(xout, format='(i5)')
		widget_control, limits_get_par.y_value,set_value=string(yout, format='(i5)')
		IF button_down EQ 1 THEN BEGIN
			wset, limits_get_par.image_win
; -- Erase the old box.
	  		Device, Copy=[0, 0, box_xsize, box_ysize, 0, 0, box_ID]
; -- Draw the new box.
	  		PlotS, [sx, sx, dummy_x, dummy_x, sx], [sy, dummy_y, dummy_y, sy, sy], /Device, $
	  			Color=box_color
	  		dummy_xsize = (dummy_x - sx)/gl_image_zoom
	  		dummy_ysize = (dummy_y - sy)/gl_image_zoom
			widget_control, limits_get_par.xsize_value,set_value=string(dummy_xsize, format='(i5)')
			widget_control, limits_get_par.ysize_value,set_value=string(dummy_ysize, format='(i5)')
		ENDIF

		IF event.type EQ 0 THEN BEGIN
; -- press mouse button to start box
			sx = event.x
			sy = event.y
			button_down = 1
			gl_region(0) = sx/gl_image_zoom
			gl_region(2) = sy/gl_image_zoom
			widget_control, limits_get_par.xmin_value,set_value=string(gl_region(0), format='(i5)')
			widget_control, limits_get_par.ymin_value,set_value=string(gl_region(2), format='(i5)')
; -- create box.
			wset, limits_get_par.image_win
			box_xsize = !D.X_VSize
			box_ysize = !D.Y_VSize
; -- Create a pixmap for erasing the box. Copy window contents into it.
			Window, /Pixmap, /Free, XSize=box_xsize, YSize=box_ysize
			box_ID = !D.Window
			Device, Copy=[0, 0, box_xsize, box_ysize, 0, 0, limits_get_par.image_win]
		ENDIF
		IF event.type EQ 1 THEN BEGIN
; -- release mouse button to obtain max limits - if 'max' limits less than 'min' limits, swap them
			button_down=0
			dummy_x = event.x/gl_image_zoom
			dummy_y = event.y/gl_image_zoom
			IF dummy_x LT gl_region(0) THEN BEGIN
				gl_region(1) = gl_region(0) & gl_region(0) = dummy_x
				widget_control, limits_get_par.xmin_value,set_value=string(gl_region(0), format='(i5)')
			ENDIF ELSE BEGIN
				gl_region(1) = dummy_x
			ENDELSE
			IF dummy_y LT gl_region(2) THEN BEGIN
				gl_region(3) = gl_region(2) & gl_region(2) = dummy_y
				widget_control, limits_get_par.ymin_value,set_value=string(gl_region(2), format='(i5)')
			ENDIF ELSE BEGIN
				gl_region(3) = dummy_y
			ENDELSE
			widget_control, limits_get_par.xmax_value,set_value=string(gl_region(1), format='(i5)')
			widget_control, limits_get_par.ymax_value,set_value=string(gl_region(3), format='(i5)')
			button_down=0
		ENDIF
	END
;
	limits_get_par.filename_display_list_label : BEGIN
		i_file = widget_info(limits_get_par.filename_display_list_label, /droplist_select)
		tif_convert_limits_get_imgdisp
		widget_control, limits_get_par.filename_display_list_label, set_droplist_select=i_file
	END
;
	limits_get_par.prev_image_label : BEGIN
		IF i_file GT 0 THEN i_file = i_file-1
		tif_convert_limits_get_imgdisp
		widget_control, limits_get_par.filename_display_list_label, set_droplist_select=i_file
	END
;
	limits_get_par.next_image_label : BEGIN
		IF i_file LT n_file-1 THEN i_file = i_file +1
		tif_convert_limits_get_imgdisp
		widget_control, limits_get_par.filename_display_list_label, set_droplist_select=i_file
	END
;
	limits_get_par.cancel_label : BEGIN
; -- cancel button, return with original region values
		gl_region = org_region
		widget_control, Event.top, /DESTROY
	END
;
	limits_get_par.finish_label : BEGIN
; -- finish button, return with updated values
		widget_control, Event.top, /DESTROY
	END
;
ENDCASE
END
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro tif_convert_gl_dialogue
; -- create and register the widget
;  called by : tif_convert_limits_get
;              not clear whether it is necessary to make this a separate widget, but it works
;
;
;  returns : region
on_error,2
COMMON limits_get_common
@tif_convert_com
@axis_com
@bsif_com
;
IF (n_tags(limits_get_par) EQ 0) THEN BEGIN
  limits_get_par = $
  { limits_get_par	,$
  	main_base			: 0L,$
	x_value				: 0L,$
	y_value				: 0L,$
	xsize_value			: 0L,$
	ysize_value			: 0L,$
	xmin_value			: 0L,$
	xmax_value			: 0L,$
	ymin_value			: 0L,$
	ymax_value			: 0L,$
  	image_label			: 0L,$
	image_win			: 0L,$
  	filename_display_list_label	: 0L,$
  	prev_image_label		: 0L,$
  	next_image_label		: 0L,$
  	cancel_label			: 0L,$
  	finish_label			: 0L }
ENDIF
;
; -- requires to be /modal call as otherwise tif_convert continues without accepting undated limits values
;
limits_get_par.main_base = widget_base(title='Conversion Area Selector', $
	/column, /modal, group_leader=tif_convert_par.main_base)
row = widget_base(limits_get_par.main_base, /row, /base_align_center)
col1 = widget_base(row, /column, /base_align_center)
col2 = widget_base(row, /column, /base_align_center)
col1a = widget_base(col1, /column, /frame, scr_xsize=80, /base_align_center)
LBL_tmp = widget_label(col1a, value='X position')
limits_get_par.x_value=widget_text(col1a, value='0', xsize=7)
LBL_tmp = widget_label(col1a, value='Y position')
limits_get_par.y_value=widget_text(col1a, value='0', xsize=7)
LBL_tmp = widget_label(col1a, value='Box X width')
limits_get_par.xsize_value=widget_text(col1a, value='0', xsize=7)
LBL_tmp = widget_label(col1a, value='Box Y width')
limits_get_par.ysize_value=widget_text(col1a, value='0', xsize=7)
col1b = widget_base(col1, /column, /frame, scr_xsize=80, /base_align_center)
LBL_tmp = widget_label(col1b, value='X min')
limits_get_par.xmin_value=widget_text(col1b, value=string(gl_region(0), format='(i5)'), xsize=7)
LBL_tmp = widget_label(col1b, value='Y min')
limits_get_par.ymin_value=widget_text(col1b, value=string(gl_region(2), format='(i5)'), xsize=7)
LBL_tmp = widget_label(col1b, value='X max')
limits_get_par.xmax_value=widget_text(col1b, value=string(gl_region(1), format='(i5)'), xsize=7)
LBL_tmp = widget_label(col1b, value='Y max')
limits_get_par.ymax_value=widget_text(col1b, value=string(gl_region(3), format='(i5)'), xsize=7)
;
limits_get_par.image_label = widget_draw(col2,xsize=n_cols*gl_image_zoom, ysize=n_rows*gl_image_zoom,$
	retain=2,/button_events,/motion,/align_center)
limits_get_par.filename_display_list_label = widget_droplist(col2, value = 'Select File', /align_center,$
	scr_xsize=250)
limits_get_par.prev_image_label = widget_button(col2, value='Display Previous Image', scr_xsize=200)
limits_get_par.next_image_label = widget_button(col2, value='Display Next Image', scr_xsize=200)
row2 = widget_base(col2, /row)
limits_get_par.cancel_label = widget_button(row2,value='Cancel', scr_xsize=90)
limits_get_par.finish_label = widget_button(row2,value='Return', scr_xsize=90)
;
widget_control, limits_get_par.main_base, /realize
widget_control, limits_get_par.image_label,get_value=window
limits_get_par.image_win = window
widget_control, limits_get_par.filename_display_list_label, set_value = gl_filelist
tif_convert_limits_get_imgdisp
xmanager, 'tif_convert_gl_dialogue', limits_get_par.main_base
return
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro tif_convert_limits_get, filelist
; -- routine to display an image and select a square or rectangular area
;    for conversion to ncdf file format
;
;  called by : tif_convert
;
;
;  returns : region
on_error,2
COMMON limits_get_common
@tif_convert_com
@axis_com
@bsif_com
;IF filelist ='' THEN GOTO, terminate
cd, tif_path, CURRENT=dummy_dir
gl_image_zoom = 0.33
i_file = 0
n_file = n_elements(filelist)
gl_filelist = filelist
gl_region = tif_region
org_region = tif_region
button_down = 0
box_color = (!D.N_Colors - 1) < 255
n_cols = 1024
n_rows = 1024
tif_convert_gl_dialogue
tif_region = gl_region
terminate:
cd, dummy_dir
return
end
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro tif_convert_event, event
@tif_convert_com
on_error, 2
@axis_com
@stack_process_com
@bsif_com
COMMON volume_data, image_stack
;
CASE event.id OF

	tif_convert_par.microscope : BEGIN
		microscope_num = widget_info(tif_convert_par.microscope, /DROPLIST_SELECT)
	    if microscope_num EQ 0 then microscope = 'Lox'
		if microscope_num EQ 1 then microscope = 'Sphinx'
		if microscope_num EQ 2 then microscope = 'ALS-PEEM2'
		if microscope_num EQ 3 then microscope = 'ALS-PEEM3'
		if microscope_num EQ 4 then microscope = 'ALS-pre-Sep02'
		if microscope_num EQ 5 then microscope = 'Saga-LS-Elmitec'
		if microscope_num EQ 6 then microscope = 'Other'

; change default values to those of the selected microscope
		if microscope EQ 'Lox' then begin
			bits12 = 0				; 16-bit unsigned tif files
			tif_signed = 1			; signed integer format
			CCD_Bgnd = 54.0			; current average background in CaPeRS camer
			Lox_flag = 1			; set Lox flag to 1
		endif

		if microscope EQ 'Sphinx' then begin
			bits12 = 0				; 16-bit unsigned tif files
			tif_signed = 1			; signed integer format
			CCD_Bgnd = 54.0			; current average background in CaPeRS camer
			Lox_flag = 0			; not Lox
		endif

		if microscope EQ 'ALS-PEEM2' then begin
			bits12 = 0				; 16-bit unsigned tif files
			tif_signed = 0			; unsigned integer format
			CCD_Bgnd = 0.0			; average background (assume removed by auto dark correction)
			Lox_flag = 0			; not Lox
		endif

		if microscope EQ 'ALS-PEEM3' then begin
			bits12 = 0				; 16-bit unsigned tif files
			tif_signed = 0			; unsigned integer format
			CCD_Bgnd = 0.0			; average background (assume removed by auto dark correction)
			Lox_flag = 0			; not Lox
		endif

		if microscope EQ 'ALS-pre-Sep02'  then begin
			bits12 = 1				; 12-bit signed tif files
			tif_signed = 1			; signed integer format
			CCD_Bgnd = 0.0			; average background (assume removed by auto dark correction)
			Lox_flag = 0			; not Lox
		endif

		if microscope EQ 'Saga-LS-Elmitec' then begin
			bits12 = 0				; 16-bit unsigned tif files
			tif_signed = 0			; unsigned integer format
			CCD_Bgnd = 54.0			; current average background in CaPeRS camer
			Lox_flag = 0			; not Lox
		endif



	if microscope EQ 'Other'  then begin
			Lox_flag = 0			; for use elsewhere
	endif

; ------------- set modified values in form -----------------
; ----- set number of bits
		IF bits12 EQ 1 then begin
		   widget_control, tif_convert_par.bits12_button, set_value='12'
		ENDIF ELSE BEGIN
		   widget_control, tif_convert_par.bits12_button, set_value='16'
		ENDELSE

; signed / unsigned --------
		IF tif_signed EQ 0  THEN BEGIN
		   widget_control, tif_convert_par.signed_button, set_value='unsigned'
		ENDIF ELSE BEGIN
		   widget_control, tif_convert_par.signed_button, set_value=' signed '
		ENDELSE

; CCD background value ----------
		widget_control, tif_convert_par.ccd_bgnd_button, set_value=string(ccd_bgnd, format='(F5.1)')

; Lox flag ---------------------
;		if lox_flag  EQ 1 then BEGIN
;		   widget_control, tif_convert_par.lox_label, set_value=' lox '
;		   widget_control, tif_convert_par.lox_button, set_value='change to other'
;		ENDIF ELSE BEGIN
;		   widget_control, tif_convert_par.lox_label, set_value='other'
;		   widget_control, tif_convert_par.lox_button, set_value='change to lox'
;		ENDELSE

	    print, 'changed default paramaters to those of ', microscope
	END
;
	tif_convert_par.pix_siz : BEGIN
		widget_control, tif_convert_par.pix_siz, get_value=dummy
		pix_siz_nm = float(dummy(0))
		pix_siz = pix_siz_nm*0.001
		widget_control, tif_convert_par.pix_siz, set_value=string(pix_siz_nm, format='(f5.1)')

	END
;
	tif_convert_par.normalize : BEGIN
		if norm_flag EQ 1 then norm_flag = 0 else  norm_flag = 1
		print, ' normalzation status changed to ', norm_flag
		 id = widget_info(Event.top, FIND_BY_UNAME = 'tif_convert_par.normalize')
		 WIDGET_CONTROL,id, set_button=norm_flag
	END
;
	tif_convert_par.bits12_button : BEGIN
		temp_string = ''
		widget_control, tif_convert_par.bits12_button, get_value=temp_string
		IF temp_string EQ '12' THEN BEGIN
		   bits12 = 0
		   widget_control, tif_convert_par.bits12_button, set_value='16'
		ENDIF ELSE BEGIN
		   bits12 = 1
		   widget_control, tif_convert_par.bits12_button, set_value='12'
		ENDELSE
	END
;
	tif_convert_par.smth_button : BEGIN
		temp_string = ''
		widget_control, tif_convert_par.smth_button, get_value=temp_string
		IF temp_string EQ ' ON ' THEN BEGIN
		   smth = 0
		   widget_control, tif_convert_par.smth_button, set_value=' OFF'
		ENDIF ELSE BEGIN
		   smth = 1
		   widget_control, tif_convert_par.smth_button, set_value=' ON '
		ENDELSE
	END
;
	tif_convert_par.bin_value : BEGIN
		widget_control, tif_convert_par.bin_value, get_value=dummy
		bin = float(dummy(0))
		bin_siz_text = 'Bin size = '+string(bin, format='(i4)')
		widget_control, tif_convert_par.bin_label, set_value=bin_siz_text
	END
;
;	tif_convert_par.lox_button : BEGIN
;		widget_control, tif_convert_par.lox_label, get_value=dummy
;		if dummy EQ 'other' then BEGIN
;		   lox_flag = 1
;		   widget_control, tif_convert_par.lox_label, set_value=' lox '
;		   widget_control, tif_convert_par.lox_button, set_value='change to other'
;		ENDIF ELSE BEGIN
;		   lox_flag = 0
;		   widget_control, tif_convert_par.lox_label, set_value='other'
;		   widget_control, tif_convert_par.lox_button, set_value='change to lox'
;		ENDELSE
;	END
;
	tif_convert_par.ccd_bgnd_button : BEGIN
		widget_control, tif_convert_par.ccd_bgnd_button, get_value=dummy
		ccd_bgnd = float(dummy(0))
		widget_control, tif_convert_par.ccd_bgnd_button, set_value=string(ccd_bgnd, format='(F5.1)')
	END
;
	tif_convert_par.signed_button : BEGIN
		temp_string = ''
		widget_control, tif_convert_par.signed_button, get_value=temp_string
		IF temp_string EQ 'unsigned' THEN BEGIN
		   tif_signed = 1
		   widget_control, tif_convert_par.signed_button, set_value=' signed '
		ENDIF ELSE BEGIN
		   tif_signed = 0
		   widget_control, tif_convert_par.signed_button, set_value='unsigned'
		ENDELSE
	END
;
;
	tif_convert_par.ncb_button : BEGIN
		temp_string = ''
		widget_control, tif_convert_par.ncb_button, get_value=temp_string
		IF temp_string EQ 'binary (ncb)' THEN BEGIN
		   ncb_switch = 0
		   widget_control, tif_convert_par.ncb_button , set_value='separate files (nc)'
		ENDIF ELSE BEGIN
		   ncb_switch = 1
		   widget_control, tif_convert_par.ncb_button , set_value='binary (ncb)'
		ENDELSE
	END
;
	tif_convert_par.ccd_corr_button : BEGIN
		white= pickfile2(title = 'Select CCD Correction File', $
	           filter='*.tif', /LPATH, DEFPATH=defpath )
;		dummy = strpos(white, codepath, /reverse_search)
; (28-jul-02 aph) keyword /reverse_search not implemented in IDL5.2)
		dummy = rstrpos(white, codepath)
		white_path = strmid(white, 0, dummy)
		white_fileonly = strmid(white, dummy+1)
		widget_control, tif_convert_par.ccd_corr_file,set_value=white_fileonly
		widget_control, tif_convert_par.ccd_corr_path,set_value=white_path
	END
;
; -------------------- get energies of the images ------------
	tif_convert_par.spectrum_button : BEGIN
		widget_control, tif_convert_par.spectrum_path, get_value=dummy
		spectrum_path = dummy(0)
		IF spectrum_path NE '' THEN cd, spectrum_path

; ------- adapt for Lox and Saga-LSLS format spectral files ------------------
		if lox_flag EQ 1 then filt='*.lox'  else filt='*.dat'
		if microscope EQ 'Saga-LS-Elmitec' then filt ='*.txt'
		spectrum_file=pickfile2(title = ' Select spectrum file', $
	           filter=filt, /LPATH, DEFPATH=defpath )
		t = ax_name(spectrum_file)
		spectrum_path = t(0)
		fileshort = t(1)
		IF spectrum_file NE '' THEN spectrum_flag = 1 ELSE spectrum_flag = 0
		gotalist = widget_info(tif_convert_par.tif_filelist, /list_select)
		IF spectrum_flag EQ 1 AND gotalist(0) NE -1 THEN BEGIN
			widget_control, tif_convert_par.convert_button, sensitive=1
		ENDIF ELSE BEGIN
			widget_control, tif_convert_par.convert_button, sensitive=0
		ENDELSE
		widget_control, tif_convert_par.spectrum_file,set_value=fileshort
		widget_control, tif_convert_par.spectrum_path,set_value=spectrum_path
	END
;
	tif_convert_par.xmin_entry : BEGIN
		widget_control, tif_convert_par.xmin_entry, get_value=dummy
		tif_region(0) = float(dummy)
		IF tif_region(0) GE tif_region(1) THEN BEGIN
			tif_region(0) = tif_region(1)-1
			widget_control, tif_convert_par.xmin_entry, set_value=string(tif_region(0),format='(i5)')
		ENDIF
		xmin_text = string(tif_region(0), format='(i5)')
		widget_control, tif_convert_par.xmin_label, set_value=xmin_text
	END
;
	tif_convert_par.ymin_entry : BEGIN
		widget_control, tif_convert_par.ymin_entry, get_value=dummy
		tif_region(2) = float(dummy)
		IF tif_region(2) GE tif_region(3) THEN BEGIN
			tif_region(2) = tif_region(3)-1
			widget_control, tif_convert_par.ymin_entry, set_value=string(tif_region(2),format='(i5)')
		ENDIF
		ymin_text = string(tif_region(2), format='(i5)')
		widget_control, tif_convert_par.ymin_label, set_value=ymin_text
	END
;
	tif_convert_par.xmax_entry : BEGIN
		widget_control, tif_convert_par.xmax_entry, get_value=dummy
		tif_region(1) = float(dummy)
		IF tif_region(1) LE tif_region(0) THEN BEGIN
			tif_region(1) = tif_region(0)+1
			widget_control, tif_convert_par.xmax_entry, set_value=string(tif_region(1),format='(i5)')
		ENDIF
		xmax_text = string(tif_region(1), format='(i5)')
		widget_control, tif_convert_par.xmax_label, set_value=xmax_text
	END
;
	tif_convert_par.ymax_entry : BEGIN
		widget_control, tif_convert_par.ymax_entry, get_value=dummy
		tif_region(3) = float(dummy)
		IF tif_region(3) LE tif_region(2) THEN BEGIN
			tif_region(3) = tif_region(2)+1
			widget_control, tif_convert_par.ymax_entry, set_value=string(tif_region(3),format='(i5)')
		ENDIF
		ymax_text = string(tif_region(3), format='(i5)')
		widget_control, tif_convert_par.ymax_label, set_value=ymax_text
	END
;
	tif_convert_par.limits_get_button : BEGIN
		tif_convert_limits_get, filename_list2
;		print,'Returned from tif_convert_limits_get...'
		xmin_text = string(tif_region(0), format='(i5)')
		widget_control, tif_convert_par.xmin_label, set_value=xmin_text
		widget_control, tif_convert_par.xmin_entry, set_value=xmin_text
		xmax_text = string(tif_region(1), format='(i5)')
		widget_control, tif_convert_par.xmax_entry, set_value=xmax_text
		widget_control, tif_convert_par.xmax_label, set_value=xmax_text
		ymin_text = string(tif_region(2), format='(i5)')
		widget_control, tif_convert_par.ymin_entry, set_value=ymin_text
		widget_control, tif_convert_par.ymin_label, set_value=ymin_text
		ymax_text = string(tif_region(3), format='(i5)')
		widget_control, tif_convert_par.ymax_label, set_value=ymax_text
		widget_control, tif_convert_par.ymax_entry, set_value=ymax_text
		END
;
	tif_convert_par.limits_set_button : BEGIN
		file_in = tif_path + filename_list2(0)

		CASE microscope OF
			'Lox' 		: 		t_img = img_load(file=file_in, /lox, /values)
			'Sphinx'	: 		t_img = rd_peem(file_in,/energy, scale=0.06)
			'Saga-LS-Elmitec' : t_img = rd_peem(file_in, bits12=0, energy=1, scale=1)
			'ALS-PEEM2' : 		t_img = rd_peem(file_in,/energy, scale=0.06)
			'ALS-PEEM3' : 		t_img = read_peem3(file=file_in,  group=axis_ID)
			'ALS-pre-Sep02' :  	t_img = rd_peem(file_in,/energy, scale=0.06)
		ENDCASE
		t = size(t_img.d)
		nx = t(1)  &  ny = t(2)
		tif_region(0) = 0
		tif_region(1) = nx
		tif_region(2) = 0
		tif_region(3) = ny
		xmin_text = string(tif_region(0), format='(i5)')
		widget_control, tif_convert_par.xmin_label, set_value=xmin_text
		widget_control, tif_convert_par.xmin_entry, set_value=xmin_text
		xmax_text = string(tif_region(1), format='(i5)')
		widget_control, tif_convert_par.xmax_entry, set_value=xmax_text
		widget_control, tif_convert_par.xmax_label, set_value=xmax_text
		ymin_text = string(tif_region(2), format='(i5)')
		widget_control, tif_convert_par.ymin_entry, set_value=ymin_text
		widget_control, tif_convert_par.ymin_label, set_value=ymin_text
		ymax_text = string(tif_region(3), format='(i5)')
		widget_control, tif_convert_par.ymax_label, set_value=ymax_text
		widget_control, tif_convert_par.ymax_entry, set_value=ymax_text
		END
;
	tif_convert_par.tif_folder_button : BEGIN
		old_tif_path = tif_path
	    if microscope EQ 'ALS-PEEM3' then fltr = '*.P3B' else fltr = '*.tif'
		t = pickfile2(title = ' Select any file to define Folder for input TIF files', $
	           filter=fltr, /LPATH, DEFPATH=defpath )
	    t = ax_name(t)  & tif_path = t(0)
;		tif_path = dialog_pickfile(/directory,Filter = '*.tif', PATH=DefPath, $
;		              GET_PATH=DefPath, title='Select any file to define Folder for input TIF files')
		widget_control, tif_convert_par.tif_folder_label,set_value=tif_path
		cd, tif_path
; -- display all tif (or *.p3b) files in directory selected ------------------------------------
		filename_list2 = findfile(fltr)
		IF filename_list2(0) NE '' THEN BEGIN
			n_tif_files = n_elements(filename_list2)
		ENDIF ELSE BEGIN
			n_tif_files = 0
		ENDELSE
; -------- sort names ---------------------------------
;  for new ALS & SPHINX PEEM - numbers between '#' and '.' ------ (%%%)
;  for Lox (18-may-04)   - numbers between '-' and '.' -------  (variable length)
;          after 20-may04 - numbers between '#' and '.' -------  (variable length)
;  for other - assumes 3 character pattern just before '.'

		IF n_tif_files GT 0 THEN BEGIN
			filename_list2 = ax_sort_names(filename_list2)

	; ----- set the limits for the image to the size of the first tif file, unless previously defined
			if n_elements(tif_region) EQ 0 then begin
				file_in = tif_path + filename_list2(0)
;				print, 'file_in = ', file_in
				CASE microscope OF
					'Lox' 		: t_img = img_load(file=file_in, /lox, /values)
					'Sphinx'	: t_img = rd_peem(file_in,/energy, scale=0.06)
					'ALS-PEEM2' : t_img = rd_peem(file_in,/energy, scale=0.06)
					'ALS-PEEM3' : t_img = read_peem3(file=file_in,  group=axis_ID)
					'ALS-pre-Sep02' :  t_img = rd_peem(file_in,/energy, scale=0.06)
					'Saga-LS-Elmitec'  : t_img = img_load(file=file_in, /values)
					'Sphinx'	: t_img = rd_peem(file_in,/energy, scale=0.06)
					'Other' 	:  t_img = rd_peem(file_in,/energy, scale=0.06)
				ENDCASE
				t = size(t_img.d)
				nx = t(1)  &  ny = t(2)
				tif_region(0) = 0
				tif_region(1) = nx
				tif_region(2) = 0
				tif_region(3) = ny
				xmin_text = string(tif_region(0), format='(i5)')
				widget_control, tif_convert_par.xmin_label, set_value=xmin_text
				widget_control, tif_convert_par.xmin_entry, set_value=xmin_text
				xmax_text = string(tif_region(1), format='(i5)')
				widget_control, tif_convert_par.xmax_entry, set_value=xmax_text
				widget_control, tif_convert_par.xmax_label, set_value=xmax_text
				ymin_text = string(tif_region(2), format='(i5)')
				widget_control, tif_convert_par.ymin_entry, set_value=ymin_text
				widget_control, tif_convert_par.ymin_label, set_value=ymin_text
				ymax_text = string(tif_region(3), format='(i5)')
				widget_control, tif_convert_par.ymax_label, set_value=ymax_text
				widget_control, tif_convert_par.ymax_entry, set_value=ymax_text
			endif

	; -- set filebase name for output files, if not already defined -----------------------------------------
			widget_control, tif_convert_par.nc_filebase_label, get_value=dummy
			nc_filebase= dummy(0) ; (28-jul-02 aph)
	;			 strjoin(dummy, /single) ; - STRJOIN does not work in 5.2
			IF nc_filebase EQ '' THEN BEGIN
				nc_filebase = 't_'
				widget_control, tif_convert_par.nc_filebase_label, set_value = nc_filebase
			ENDIF
	; -- default is to start with paths for all other files the same as the input path, --------------------
	;             unless the path is already specified --------------------
			widget_control, tif_convert_par.nc_folder_label, get_value=dummy
			nc_path=dummy(0)
			IF nc_path EQ '' OR nc_path EQ old_tif_path THEN BEGIN
				nc_path = tif_path
				widget_control, tif_convert_par.nc_folder_label,set_value=nc_path
			ENDIF
			widget_control, tif_convert_par.spectrum_path, get_value=dummy
			spectrum_path=dummy(0)
			IF spectrum_path EQ '' OR spectrum_path EQ old_tif_path THEN BEGIN
				spectrum_path = tif_path
				widget_control, tif_convert_par.spectrum_path,set_value=spectrum_path
			ENDIF
			widget_control, tif_convert_par.tif_select_all, sensitive=1
			widget_control, tif_convert_par.limits_get_button, sensitive=1
			widget_control, tif_convert_par.limits_set_button, sensitive=1
		ENDIF ELSE BEGIN
			widget_control, tif_convert_par.tif_select_all, sensitive=0
			widget_control, tif_convert_par.limits_get_button, sensitive=0
			widget_control, tif_convert_par.limits_set_button, sensitive=0
		ENDELSE
		widget_control, tif_convert_par.tif_filelist, set_value=filename_list2
	END
;
	tif_convert_par.tif_select_all : BEGIN
	    dummys=size(filename_list2)
		dummy=make_array(dummys[1], /index, /int)
		widget_control, tif_convert_par.tif_filelist, set_list_select=dummy
; if there is a spectrum name, then ready togo, so sensitize the 'convert' button
		gotalist = widget_info(tif_convert_par.tif_filelist, /list_select)
		IF spectrum_flag EQ 1 AND gotalist(0) NE -1 THEN BEGIN
			widget_control, tif_convert_par.convert_button, sensitive=1
		ENDIF ELSE BEGIN
			widget_control, tif_convert_par.convert_button, sensitive=0
		ENDELSE
	END
;
	tif_convert_par.nc_folder_button : BEGIN
		t = pickfile2(title = ' Select folder for output files', $
	           filter='*.nc*', /LPATH, DEFPATH=defpath )
	    t = ax_name(t)  & nc_path = t(0)
;		nc_path = dialog_pickfile(/directory,  PATH=DefPath, $
;		              GET_PATH=DefPath,title='Select Folder for output .NC files', /write)
		widget_control, tif_convert_par.nc_folder_label,set_value=nc_path
		cd, nc_path
		nc_files_list = findfile('*.nc')
		widget_control, tif_convert_par.nc_filelist, set_value=nc_files_list
	END
;
	tif_convert_par.nc_filebase_label : BEGIN
		widget_control, tif_convert_par.nc_filebase_label, get_value=dummy
		nc_filebase= dummy(0) ; (28-jul-02 aph)
;			 strjoin(dummy, /single) ; - STRJOIN does not work in 5.2

	END
;
	tif_convert_par.tif_filelist : BEGIN
		gotalist = widget_info(tif_convert_par.tif_filelist, /list_select)
		IF gotalist(0) NE -1 AND spectrum_flag EQ 1 THEN BEGIN
			widget_control, tif_convert_par.convert_button, sensitive=1
		ENDIF ELSE BEGIN
			widget_control, tif_convert_par.convert_button, sensitive=0
		ENDELSE
	END
;
; ***********************************************************************************
;
;                    PROCESSING . . ..
; ***********************************************************************************
;
	tif_convert_par.convert_button : BEGIN
		; get list of selected files
		; check have selected at least one file, if not return
		; get energies from spectrum file
		; check if number of energies in file and number of images the same
		;     - if not, ask user what to do
		; do the conversion
		; append each output file to .nc_filelist as we go
		; write .sl file
		gain=1

; ----- get bin value -----------
		widget_control, tif_convert_par.bin_value, get_value=dummy
		bin = float(dummy(0))

	CASE microscope OF		; (aph 11-Mar-13:  converted specific if's to a CASE structure CAUTION for errors)
		'Lox': begin

; ------ lox stack read-in : different from rest ------------------- (aph 18-may-04)
			e_tmp = read_lox_spectra(file=spectrum_file)
			no_files_convert = n_elements(gotalist)
; ---- check if (1) spectral read-in worked; (2) numbers of E, images are the same -------------
; --- abandon read with error message if not -----------
			IF n_tags(e_tmp) EQ 0 THEN RETURN
			if n_elements(e_tmp.x) NE no_files_convert then begin
				text = 'Mismatch in # of energies (' + strtrim(string(fix(n_elements(e_tmp.x))),2)
				text = text + ') and # of files (' + strtrim(string(fix(no_files_convert)),2) + ')'
				axis_log, text
				return
			endif

;			t_dir = dialog_message(/question,'Scanned high-E to low-E ?', Default_No=1)
;			if t_dir EQ 'Yes' then E_vals = reverse(e_tmp.x) else E_vals = e_tmp.x

			out_filelist = make_array(no_files_convert, /string)
			start_file_no = gotalist(0)
			end_file_no = gotalist(no_files_convert-1)
			file_in = tif_path + filename_list2(start_file_no)
			lox_img = img_load(file=file_in, /lox, /values)
	;		help, lox_img,/structure
			tif_region = fix(tif_region)
	;		print, tif_region
			t_img = lox_img.d(tif_Region(0):tif_region(1)-1,tif_Region(2):tif_region(3)-1)
			t = size(t_img)
			nx = t(1) & ny = t(2) & no_energies = no_files_convert
			image_stack = fltarr(nx, ny, no_energies)
			filename_ev_msec_list = strarr(no_energies)
	;		print, 'Reading ', no_energies, 'images into 3-d array '
			FOR i_file = start_file_no, End_file_no DO BEGIN
				file_in = tif_path + filename_list2(i_file)
				e_file = i_file - start_file_no			; correct for offsets; assumes E's in order!
				IF strlen(file_in) GT 0 THEN BEGIN
	;				print,' Processing file ', fix(i_file), '. . . ', file_in
					lox_img = img_load(file=file_in, /lox, /values)
					t_img = lox_img.d(tif_Region(0):tif_region(1)-1,tif_Region(2):tif_region(3)-1)
					if  smth EQ 1 then t_img = median(t_img,3)
					image_stack(*,*,e_file) = t_img - ccd_bgnd
		; -- FORCE 3-character scheme with no blanks !!
					zero = '000'
					t_num = strtrim(strcompress(string(e_file+1)),2)
					strput, zero, t_num, 3-strlen(t_num)
					file_out = strlowcase(nc_filebase + zero) + '.nc'
					spos=rstrpos(file_out,codepath)
					fileshort = strmid(file_out,spos+1,strlen(file_out))
					filename_ev_msec_list(e_file) = filename_list2(i_file) + ' ' + $
				    			string(E_vals(i_file), format = '(F8.2)')
					out_filelist(i_file-start_file_no) = file_out
					widget_control, tif_convert_par.nc_filelist, set_value=out_filelist
				ENDIF
			ENDFOR
		END
;
; ------ Saga-LS energy read-in -------------------------------

		'Saga-LS-Elmitec': BEGIN
			if file_Test(spectrum_file) GT 0 then $
				 energy = gen_E(file=spectrum_file) else energy = gen_E
		 	if n_elements(energy) GT 0 then begin
		 		d=fltarr(n_elements(energy))
		 		e_tmp={t:'1d', d:d, x: energy, xl: '', dn: d, dl: 'Saga-LS'}
		 	endif else begin
		 		axis_log, 'Problem with reading (start,step) energy limits file'
		 		return
		 	endelse
		END
; ------ ALS-PEEM3 energy read in --------
		'ALS-PEEM3' : e_tmp = read_p3b_spectrum(file=spectrum_file, /silent)

;  --- Energy READ_IN for other data formats -------------
		ELSE : e_tmp = pem_load(file=spectrum_file)
		ENDCASE

; -----------  OK, now have an energy list for the set of images in the stack

		t_dir = dialog_message(/question,'Scanned high-E to low-E ?')
		if t_dir EQ 'Yes' then E_vals = reverse(e_tmp.x) else $
			E_vals = e_tmp.x

		no_files_convert = n_elements(gotalist)

		print, '# of files = ', no_files_convert
		print, '# of energies = ', n_elements(e_tmp.x)

		start_file_no = gotalist(0)
		end_file_no = gotalist(no_files_convert-1)
		out_filelist = make_array(no_files_convert, /string)
		widget_control, tif_convert_par.convert_button, sensitive=0
; check for missing energies (problem in sphinx - misses one energy !!) (aph kluge: 30-apr-03)
		if no_files_convert GT n_elements(E_vals) then begin
			if no_files_convert - n_elements(E_vals) EQ 1 then begin
				print, 'WARNING: Energy spectrum and file selection mismatch'
				no_files_convert = no_files_convert -1
				End_file_no = End_file_no - 1
			endif else begin
				print, 'ERROR: Energy spectrum and file selection mismatch'
				return
			endelse
		endif
;		print, ' converting', no_files_convert,' files: ', start_file_no,' = ', filename_list2(start_file_no), ' to ', $
;				 end_file_no, ' = ', filename_list2(end_file_no)

; ---- since an explicit call with SCALE is made, this defines 'REGION' in terms of micron real space units, NOT pixel unit
; -  here the pixel units are converted to real space equivalents
	pix_siz = pix_siz_nm / 1000.		; use nm internally but Tifrd_im uses microns
	tif_region = pix_siz*tif_region		; region defined in tif_convert is in PIXELS but rd_peem requires it in DATA units in microns
;                                       ; UNDO after reading all data so it contains pixels
	print, 'pix_siz_nm ' , pix_siz_nm
	print, 'tif_region to extract ', tif_region
	CCB_bgn_file = white ; (10-may-03) for now, assume people will use the correction file for background, not WHITE

; -------- to store all image_data in 1 array need to determine array size
		if ncb_switch EQ 1 then BEGIN
			file_in = tif_path + filename_list2(start_file_no)
;			print, 'first file = ', file_in
			; ---- read in first  file
			IF microscope EQ 'ALS-PEEM3' then begin
				test = read_Peem3(file=file_in, bin=bin, scale=pix_siz_nm,  group=axis_ID)
				nx = n_elements(test.x)
				ny = n_elements(test.y)
				no_energies = no_files_convert
				image_data = fltarr(nx, ny, 1)
			ENDIF ELSE begin
				IF bin NE 1 THEN BEGIN
					tifrd_im, file_in, bin=bin, smth=smth, bits12 = bits12, scale=pix_siz,  $
						gain = gain, CCD_bgnd=CCD_bgnd_file,  energy=E_vals(0), $
						white=white, region = tif_region
				ENDIF ELSE BEGIN
					 tifrd_im, file_in, smth=smth, bits12 = bits12, scale=pix_siz, $
					 	gain = gain, CCD_bgnd=CCD_bgnd_file, energy=E_vals(0), $
					 	white=white, region = tif_region
				ENDELSE
				t = size(image_data)
				nx = t(1) & ny = t(2) & no_energies = no_files_convert
			endelse
			image_stack = fltarr(nx, ny, no_energies)
			filename_ev_msec_list = strarr(no_energies)
;			print, 'Reading ', no_energies, 'images into 3-d array '
		ENDIF

		print, 'bin value = ', bin
; -------------------------------------------------------- MAIN LOOP TO READ IN THE STACK ---------
		FOR i_file = start_file_no, End_file_no DO BEGIN
			file_in = tif_path + filename_list2(i_file)
			e_file = i_file - start_file_no			; correct for offsets; assumes E's in order!
			IF strlen(file_in) GT 0 THEN BEGIN
;				print,' Processing file ', fix(i_file), '. . . ', file_in
	; --  READ IN DATA
				IF microscope EQ 'ALS-PEEM3' then begin
					test = read_Peem3(file=file_in, bin=bin, scale=pix_siz_nm,  group=axis_ID)
					image_data(*,*,0)=test.d(*,*)
				ENDIF ELSE begin
					IF bin NE 1 THEN BEGIN
						tifrd_im, file_in, bin=bin, smth=smth, bits12 = bits12, scale=pix_siz,  $
							gain = gain, CCD_bgnd=CCD_bgnd_file,  energy=E_vals(i_file), $
							white=white, region = tif_region
					ENDIF ELSE BEGIN
						 tifrd_im, file_in, smth=smth, bits12 = bits12, scale=pix_siz, $
						 	gain = gain, CCD_bgnd=CCD_bgnd_file, energy=E_vals(i_file), $
						 	white=white, region = tif_region
					ENDELSE
		; correct sphinx (signed) data -without the following numbers are 32 K
					if tif_signed EQ 1 then image_data(*,*,0) = image_data(*,*,0) + 2^15
		; correct SagaLS data for sign				; KLUGE !!! - should use signed or unsigned 16-bit flag !!!
					if microscope EQ ' Saga-LS' then image_data(*,*,0) = -1.0 * image_data(*,*,0)
		; subtract dark count - assumed uniform over the image (no pattern)
					image_data(*,*,0) = image_data(*,*,0) - ccd_bgnd
					sd.wavelength = 12398.0/E_vals(i_file)
				ENDELSE
	; -- FORCE 3-character scheme with no blanks !!
				zero = '000'
				t_num = strtrim(strcompress(string(e_file+1)),2)
				strput, zero, t_num, 3-strlen(t_num)
				file_out = strlowcase(nc_filebase + zero) + '.nc'
				spos=rstrpos(file_out,codepath)
				fileshort = strmid(file_out,spos+1,strlen(file_out))
				out_filelist(i_file-start_file_no) = file_out
; optional ncb or nc write-out
				if ncb_switch EQ 1 then BEGIN
					image_stack(*,*,e_file) = image_data(*,*,0)
					filename_ev_msec_list(e_file) = filename_list2(i_file) + ' ' + $
			    			string(E_vals(i_file), format = '(F9.2)')
					out_filelist(i_file-start_file_no) = file_out
				ENDIF ELSE BEGIN
; write out individual *.nc files
					data_title = byte(fileshort)
					x_title = 'X'
					y_title = 'Y'
					image_title = byte(fileshort)
					sd.clock_frequency = 1.
					file_out = nc_path + file_out
					wrstx_ax,file_out
				ENDELSE
				widget_control, tif_convert_par.nc_filelist, set_value=out_filelist
;				print,'wrote nsls NetCDF format file: ', file_out
			ENDIF
		ENDFOR
		tif_region = tif_region/pix_siz	; UNDO so preserve pixel infor from last selection
;	ENDELSE

; -------- read-in is complete - write ncb binary or stack list file

;		print, filename_ev_msec_list

; -------- modify energy list to correspond to the files actually converted (can be a subset)
		eV =e_vals(start_file_no: End_file_no)

		IF ncb_switch EQ 1 then BEGIN
	   		stack_file= pickfile2(title = ' Name of stack file', $
	           filter='*.ncb', /LPATH, DEFPATH=defpath )
			if stack_file EQ '' then return
     	    widget_control,hourglass=1
			t = ax_name(stack_file)
			stack_file = t(0) + t(1) + '.ncb'   ; force standard extension
			x_start = 0 & x_stop = (nx-1)*pix_siz*bin
			y_start = 0 & y_stop = (ny-1)*pix_siz*bin

;--------------  reverse data if in wrong order
		;	test = dialog_message(/question, 'Energies out of order. Sort ?')
		;	if test EQ 'No' then goto, end_ev_sort
			sort_ev = sort(ev)
			timg = image_stack
			tlbl = filename_ev_msec_list
			for i = 0,n_elements(ev)-1 do begin
				image_stack(*,*,i) = timg(*,*,sort_ev(i))
				filename_ev_msec_list(i) = tlbl(sort_ev(i))
			endfor
			ev = ev(sort(ev))
			end_ev_sort:
;			print, 'No of energies ', n_elements(ev), ' No of files to convert ',no_files_convert
; ---------- edit filename_ev_msec_list to make compatible with alignment routines
			for i = 0,n_elements(ev)-1 do begin
;				print, filename_ev_msec_list(i), ' . . . '
				npos = rstrpos(filename_ev_msec_list(i), '#')
				if npos NE -1 then begin
					t1 = strmid(filename_ev_msec_list(i), 0, npos)
					t2 = strmid(filename_ev_msec_list(i), npos+1)
					filename_ev_msec_list(i) = t1+t2
				endif
				npos = rstrpos(filename_ev_msec_list(i), '-')
				if npos NE -1 then begin
					t1 = strmid(filename_ev_msec_list(i), 0, npos)
					t2 = strmid(filename_ev_msec_list(i), npos+1)
					filename_ev_msec_list(i) = t1+t2
				endif
				npos = strpos(filename_ev_msec_list(i), '.tif')
				if npos NE -1 then begin
					t1 = strmid(filename_ev_msec_list(i), 0, npos)
					t2 = strmid(filename_ev_msec_list(i), npos+4)
					filename_ev_msec_list(i) = t1+t2
				endif
				npos = strpos(filename_ev_msec_list(i), 'tif')
				if npos NE -1 then begin
					t1 = strmid(filename_ev_msec_list(i), 0, npos)
					t2 = strmid(filename_ev_msec_list(i), npos+3)
					filename_ev_msec_list(i) = t1+t2
				endif
;			print, 'modified to ', filename_ev_msec_list(i)
			endfor

			stack_wb, stack_file
	        widget_control,hourglass=0
		ENDIF ELSE BEGIN
; -- WRITE-OUT stack list -------------------------------
					outlist = nc_path + strmid(nc_filebase,0,strlen(nc_filebase)-1) + '.sl'
			openw,unitw, outlist,/get_lun
			print, Outlist, ' file opened for stack list'
			FOR i_file = 0, no_files_convert-1  DO BEGIN
				printf, unitw, out_filelist(i_file)
			ENDFOR
			close, unitw
		ENDELSE
		close,/all		; useful to ensure logical units are available !
;
		widget_control, tif_convert_par.convert_button, sensitive=1
	END
;
	tif_convert_par.finish_button : BEGIN
		widget_control, Event.top, /DESTROY
	END
ENDCASE
END
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro tif_convert
;
on_error, 2
@axis_com
@bsif_com
@tif_convert_com
;
;
IF (n_tags(tif_convert_par) EQ 0) THEN BEGIN
  tif_convert_par = $
  { tif_convert_par	,$
  	main_base		: 0L,$
  	scale_label		: 0L,$
  	microscope		: 0L,$
  	pix_siz			: 0L,$
  	bits12_label	: 0L,$
  	bits12_button	: 0L,$
  	smth_label		: 0L,$
  	smth_button		: 0L,$
  	bin_label		: 0L,$
  	bin_value		: 0L,$
  	lox_label		: 0L,$
  	lox_button		: 0L,$
    ccd_bgnd_label 		: 0L,$
    ccd_bgnd_button		: 0L,$
  	ccd_corr_file		: 0L,$
  	ccd_corr_path		: 0L,$
  	ccd_corr_button		: 0L,$
  	spectrum_file		: 0L,$
  	spectrum_path		: 0L,$
  	spectrum_button		: 0L,$
	xmin_label 		: 0L,$
	xmax_label 		: 0L,$
	ymin_label 		: 0L,$
	ymax_label 		: 0L,$
	xmin_entry 		: 0L,$
	xmax_entry 		: 0L,$
	ymin_entry 		: 0L,$
	ymax_entry 		: 0L,$
	limits_get_button 	: 0L,$
	limits_set_button 	: 0L,$
  	tif_folder_button	: 0L,$
  	tif_folder_label	: 0L,$
  	tif_select_all		: 0L,$
  	tif_filelist		: 0L,$
  	convert_button		: 0L,$
  	nc_folder_button	: 0L,$
  	nc_folder_label		: 0L,$
	nc_filebase_label	: 0L,$
   	nc_filelist		: 0L,$
   	ncb_label       : 0L,$
   	ncb_button      : 0L,$
   	signed_label       : 0L,$
   	signed_button      : 0L,$
   	blank_label      : 0L,$
   	normalize      : 0L,$
  	finish_button		: 0L }
ENDIF
 CASE strupcase(!version.os_family) OF
	'VMS' : BEGIN
		pathsep = ']'
	END
	'WINDOWS' : BEGIN
		pathsep = '\'
	END
	'MACOS' : BEGIN
		pathsep = ':'
	END
	'UNIX' : BEGIN
		pathsep = '/'
	END
	ELSE : BEGIN
		print,'Unrecognized operating system'
	END
ENDCASE


; -------------------- set up widget ------------------------------
tif_convert_par.main_base = widget_base(title='TIF to NCDF Conversion', /column, /scroll)
row1 = widget_base(tif_convert_par.main_base, /row, /frame)
col1 = widget_base(row1, /column, /frame)
row1a = widget_base(col1, /row)
col1a = widget_base(row1a, /column, /base_align_left)
col1b = widget_base(row1a, /column, /base_align_center)
col2 = widget_base(row1, /column, scr_xsize=220, /base_align_center)
col3 = widget_base(row1, /column, scr_xsize=100, /base_align_center)
col4 = widget_base(row1, /column, scr_xsize=220, /base_align_center)

; information --------------
text = 'Lox, SPHINX files: 16-bit, signed, CCD_bgnd=54.'
LBL_tmp = widget_label(col1, value= text, /align_left)
text = 'new ALS files (>Sep-02): 16-bit, unsigned, CCD_bgnd=0.'
LBL_tmp = widget_label(col1, value= text, /align_left)
text = 'old ALS files (<Sep-02): 12-bit, unsigned'
LBL_tmp = widget_label(col1, value= text, /align_left)
text = 'Saga-LS Elmitec: 16-bit, unsigned'
LBL_tmp = widget_label(col1, value= text, /align_left)

; select microscope to auto-set multiple default paramaters
LBL_tmp = widget_label(col1a, value = 'Microscope')
microscope_list = ['Lox','Sphinx','ALS-PEEM2','ALS-PEEM3', 'ALS-pre-Sep02', 'Saga-LS-Elmitec' , 'Other']

IF N_ELEMENTS(microscope) EQ 0 THEN microscope = 'Lox'
if microscope EQ 'Lox'           then microscope_num = 0
if microscope EQ 'Sphinx'        then microscope_num = 1
if microscope EQ 'ALS-PEEM2'     then microscope_num = 2
if microscope EQ 'ALS-PEEM3'     then microscope_num = 3
if microscope EQ 'ALS-pre-Sep02' then microscope_num = 4
if microscope EQ 'Saga-LS-Elmitec' then microscope_num = 5
if microscope EQ 'Other'         then microscope_num = 6

tif_convert_par.microscope = widget_droplist(col1b, value = microscope_list, $
                    UNAME = 'droplist_microscope')  ; ', /return_full_name)
widget_control, tif_convert_par.microscope, set_droplist_select= microscope_num

LBL_tmp = widget_label(col1a, value= '  ', /align_left)

; -------- check for existence of variables; set to Lox default if do not exist -----
IF N_ELEMENTS(bits12) EQ 0 THEN bits12 = 0				; default to 16-bit unsigned tif files
IF N_ELEMENTS(microscope) EQ 0 THEN microscope = 'Lox'
IF N_ELEMENTS(tif_signed) EQ 0 THEN tif_signed = 1		; default to unsigned integer format
IF N_ELEMENTS(CCD_Bgnd) EQ 0 THEN CCD_Bgnd = 54.0		; current average background in CaPeRS camer
IF N_ELEMENTS(Lox_flag) EQ 0 THEN Lox_flag = 1
IF N_ELEMENTS(pix_siz_nm) EQ 0 THEN pix_siz_nm = 60.0	; default for 60 nm pixels; 60 um field of view for 1024x1024 camera
	pix_siz = pix_siz_nm*0.001		; NEEDED FOR USE ELSEWHERE IN PROGRAM (um)
IF N_ELEMENTS(smth) EQ 0 THEN smth = 0					; no median smoothing
IF N_ELEMENTS(bin) EQ 0 THEN bin = fix(1)				; no binning
IF N_ELEMENTS(ncb_switch) EQ 0 THEN ncb_switch = 1		; write as single binary file
IF N_ELEMENTS(white) EQ 0 THEN  white = ''
IF N_ELEMENTS(spectrum_path) EQ 0 THEN spectrum_path = ''
IF N_ELEMENTS(spectrum_file) EQ 0 THEN spectrum_file = ''
IF N_ELEMENTS(tif_path) EQ 0 THEN tif_path = ''
IF N_ELEMENTS(nc_path) EQ 0 THEN nc_path = ''
IF N_ELEMENTS(tif_region) EQ 0 THEN begin
	tif_region = fltarr(4)			; tif_region is either default from tif_convert_com or set to 0-1024
	tif_region(0) = 0
	tif_region(1) = 1024
	tif_region(2) = 0
	tif_region(3) = 1024
ENDIF

; ------------------ print default values (testing)  ------------
testing = 1
if testing EQ 1 then begin
	print, 'TIF_convert: Default values'
	print, '---------------------------'
	print, 'microscope              ', microscope
	print, 'bits12 (0=16, 1=12)     ', bits12
	print, 'tif_signed (1=unsigned) ', tif_signed
	print, 'CCD_Bgnd                ', CCD_Bgnd
	print, 'Lox_flag (1=Lox)        ', Lox_flag
	print, 'pix_siz_nm              ', pix_siz_nm
	print, 'Median smoothing(1=yes) ', smth
	print, 'binning                 ', bin,' x ', bin
	print, 'binary output (1=yes)   ', ncb_switch
endif

;  No of bits ---------------------
tif_convert_par.bits12_label = widget_label(col1a, value ='No of bits', scr_ysize=22)
if bits12 EQ 1 then text = '12' else text = '16'
tif_convert_par.bits12_button = widget_button(col1b, value = text, scr_ysize=22)

; signed / unsigned --------
tif_convert_par.signed_label = widget_label(col1a, value= 'signed/unsigned', scr_ysize=22)
if tif_signed EQ 1 then text = ' signed ' else text = 'unsigned'
tif_convert_par.signed_button = widget_button(col1b, value=text, scr_ysize=22)

; CCD background value ----------
tif_convert_par.ccd_bgnd_label = widget_label(col1a, value = 'CCD Background Count', scr_ysize=22)
tif_convert_par.ccd_bgnd_button = widget_text(col1b, value=string(ccd_bgnd, format='(F5.1)'), $
         /align_center, xsize=10, scr_ysize=22, /editable)

; Lox flag ---------------------
;if lox_flag EQ 1 then lox_text = ' lox ' else lox_text = 'other'
;tif_convert_par.lox_label = widget_label(col1a, value = lox_text, scr_ysize=22)
;if lox_flag EQ 1 then lox2_text = 'change to other' else lox2_text = 'change to lox'
;tif_convert_par.lox_button = widget_button(col1b, value=lox2_text, scr_ysize=22, /align_center)

; LBL_tmp = widget_label(col1a, value= '  ', /align_left, scr_ysize=22)

; pixel size -----------------
tif_convert_par.scale_label = widget_label(col1a, value = 'nm/pixel', scr_ysize=22)
text = string(pix_siz_nm, format='(f5.1)')
tif_convert_par.pix_siz = widget_text(col1b, value=text, xsize=10, /editable, scr_ysize=22, /align_center)

; Median smooth -------------
tif_convert_par.smth_label = widget_label(col1a, value = 'Median smoothing', scr_ysize=22)
if smth EQ 0 then $
	tif_convert_par.smth_button = widget_button(col1b, value=' OFF', scr_ysize=22) else $
		tif_convert_par.smth_button = widget_button(col1b, value=' ON ', scr_ysize=22)

; Binning -------------------
tif_convert_par.bin_label = widget_label(col1a, value = 'bin_size', scr_ysize=22)
tif_convert_par.bin_value = widget_text(col1b, value=string(fix(bin)), xsize=10, scr_ysize=22, /editable)

; Output format (separate *.nc files  versus single *.ncb file) --------------
tif_convert_par.ncb_label = widget_label(col1a, value = 'Output format', scr_ysize=22)
if ncb_switch EQ 0 then text = 'separate files (nc)' else text = '    binary (ncb)   '
tif_convert_par.ncb_button = widget_button(col1b, value=text, /align_center, scr_ysize=26)

; -------- I-ring normalize -----------------------
;tif_convert_par.Ring_norm_button = widget_label(col1a, value='I-ring normalize', /align_left, scr_ysize=22)
WID_BASE_1 = Widget_Base(col1a, UNAME='WID_BASE_1',COLUMN=1 ,/NONEXCLUSIVE)
tif_convert_par.normalize = Widget_Button(Wid_Base_1, UNAME='tif_convert_par.normalize', $
        /ALIGN_RIGHT, VALUE='I-ring norm?')
; ----------- set to current value of normalization flag
  if norm_flag EQ 1 then widget_control, tif_convert_par.normalize, set_button = 1 $
     else widget_control, tif_convert_par.normalize, set_button = 0

 LBL_tmp = widget_label(col1b, value= '  ', /align_left, scr_ysize=22)
 LBL_tmp = widget_label(col1b, value= '  ', /align_left, scr_ysize=22)


; --------spectrum file -------
tif_convert_par.spectrum_button = widget_button(col1a, value='Spectrum File', /align_left, scr_ysize=22)
LBL_tmp = widget_label(col1b, value= '         ', /align_center)
LBL_tmp = widget_label(col1b, value= '         ', /align_center)
LBL_tmp = widget_label(col1a, value='Path', /align_left, scr_ysize=22)
tif_convert_par.spectrum_path = widget_text(col1b, xsize=24, /align_center, scr_ysize=22)
LBL_tmp = widget_label(col1a, value='File', /align_left)
tif_convert_par.spectrum_file = widget_text(col1b, xsize=24, value = spectrum_file, /align_center, scr_ysize=22)

LBL_tmp = widget_label(col1a, value= '  ', /align_left)
LBL_tmp = widget_label(col1b, value= '  ', /align_left)

; -------- CCD correction file -------
tif_convert_par.ccd_corr_button = widget_button(col1a, value='CCD Correction File', /align_left, scr_ysize=22)
;LBL_tmp = widget_label(col1b, value= '         ', /align_center)
LBL_tmp = widget_label(col1b, value= '         ', /align_center)
LBL_tmp = widget_label(col1a, value='Path', /align_left, scr_ysize=22)
tif_convert_par.ccd_corr_path = widget_text(col1b, xsize=24, /align_center, scr_ysize=22)
LBL_tmp = widget_label(col1a, value='File', /align_left, scr_ysize=22)
tif_convert_par.ccd_corr_file = widget_text(col1b, xsize=24, value = white, /align_center, scr_ysize=22)


; - ------- region selected ------------------------------
base = widget_base(col1, /column, /frame)
row1b = widget_base(base, /row)
col1c = widget_base(row1b, /column, /base_align_center)
LBL_tmp = widget_label(col1c, value='X min (pixel)')
row1b1 = widget_base(col1c, /row)
tif_convert_par.xmin_label = widget_label(row1b1, value=string(tif_region(0),format='(i5)'))
tif_convert_par.xmin_entry = widget_text(row1b1, value=string(tif_region(0),format='(i5)'), xsize=7, /editable)
LBL_tmp = widget_label(col1c, value='Y min (pixel)')
row1b2 = widget_base(col1c, /row)
tif_convert_par.ymin_label = widget_label(row1b2, value=string(tif_region(2),format='(i5)'))
tif_convert_par.ymin_entry = widget_text(row1b2, value=string(tif_region(2),format='(i5)'), xsize=7, /editable)
col1d = widget_base(row1b, /column, /base_align_center)
LBL_tmp = widget_label(col1d, value='X max (pixel)')
row2b1 = widget_base(col1d, /row)
tif_convert_par.xmax_label = widget_label(row2b1, value=string(tif_region(1),format='(i5)'))
tif_convert_par.xmax_entry = widget_text(row2b1, value=string(tif_region(1),format='(i5)'), xsize=7, /editable)
tif_convert_par.ymax_label = widget_label(col1d, value='Y max (pixel)')
row2b2 = widget_base(col1d, /row)
tif_convert_par.ymax_label = widget_label(row2b2, value=string(tif_region(3),format='(i5)'))
tif_convert_par.ymax_entry = widget_text(row2b2, value=string(tif_region(3),format='(i5)'), xsize=7, /editable)

; --------- buttons to control limits
tif_convert_par.limits_get_button = widget_button(col1c, value='Set limits', /align_center)
tif_convert_par.limits_set_button = widget_button(col1d, value='Full image limits', /align_center)

; ------- exit ------------
tif_convert_par.finish_button = widget_button(col1, value='EXIT', /align_center)

; ---------- TIF file path  -----------------------
LBL_tmp = widget_label(col2, value='Input tif files', /align_center)
tif_convert_par.tif_folder_button = widget_button(col2, value='Folder', /align_center)
tif_convert_par.tif_folder_label = widget_text(col2, value = tif_path, scr_xsize=200, /align_center)

LBL_tmp = widget_label(col3, value='Select', /align_center, sensitive = select_on)
LBL_tmp = widget_label(col3, value='.TIF files for', /align_center)
LBL_tmp = widget_label(col3, value='conversion', /align_center)
tif_convert_par.convert_button = widget_button(col3, value='Convert', scr_xsize=80, sensitive=0)

; ------ output path ---------------
LBL_tmp = widget_label(col4, value='Output .nc files')
tif_convert_par.nc_folder_button = widget_button(col4, value='Folder')
tif_convert_par.nc_folder_label = widget_text(col4, value='', scr_xsize=200)
; ------- output file name -----------
LBL_tmp = widget_label(col4, value='.NC file base name')
tif_convert_par.nc_filebase_label = widget_text(col4, scr_xsize=200, value='', /editable)
tif_convert_par.nc_filelist = widget_list(col4, scr_xsize=200, scr_ysize=500)

; ---------- load TIF file list if there are files  -----------------------
LBL_tmp = widget_label(col2, value='')
tif_convert_par.tif_select_all = widget_button(col2, value='Select All', /align_center)  ;, sensitive=0)
tif_convert_par.tif_filelist = widget_list(col2, scr_xsize=200, scr_ysize=500, /multiple, /align_center)
IF tif_path NE '' THEN begin		; load list of tif files
	print, 'reading in files from last directory, ', tif_path
	if strmid(!version.os,0,3) EQ 'Win' then begin
		t_path =  strmid(tif_path, 0, strlen(tif_path)-1)	; kluge to make findflie work - NB file_inof from IDL6.0 probably better
		print, ' modified to ', t_path
	endif else t_path = tif_path
	test=strlen(findfile(t_path))
	IF fix(test(0)) GT 0 then begin ; but only if the file referred to exists
		cd, tif_path
	; -- display all tif files in directory selected ------------------------------------
		filename_list2 = findfile('*.tif')
		IF filename_list2(0) NE '' then n_tif_files = n_elements(filename_list2)

; -------- sort names ---------------------------------
;  for new ALS & SPHINX PEEM - numbers between '#' and '.' ------ (%%%)
;  for Lox (18-may-04)   - numbers between '-' and '.' -------  (variable length)
;          after 20-may04 - numbers between '#' and '.' -------  (variable length)
;  for other - assumes 3 character pattern just before '.'
		IF n_tif_files GT 0 THEN BEGIN
			filename_list2 = ax_sort_names(filename_list2)
			widget_control, tif_convert_par.tif_filelist, set_value=filename_list2
		ENDIF

; -- default is to start with paths for putput & spectra files the same as the input path, --------------------
;             unless the path is already specified --------------------
		IF nc_path EQ '' then nc_path = tif_path
		widget_control, tif_convert_par.nc_folder_label,set_value=nc_path
		IF spectrum_path EQ '' then spectrum_path = tif_path
		widget_control, tif_convert_par.spectrum_path,set_value=spectrum_path
		widget_control, tif_convert_par.tif_select_all, sensitive=1
		widget_control, tif_convert_par.limits_get_button, sensitive=1
		widget_control, tif_convert_par.limits_set_button, sensitive=1
		spectrum_flag=1
	ENDIF
ENDIF ELSE BEGIN
	widget_control, tif_convert_par.tif_select_all, sensitive=0
	widget_control, tif_convert_par.limits_get_button, sensitive=0
	widget_control, tif_convert_par.limits_set_button, sensitive=0
	spectrum_flag=0
ENDELSE

widget_control, tif_convert_par.main_base, /realize
xmanager, 'tif_convert', tif_convert_par.main_base

end
