; Copyright (c) 1998-2015 A.P. Hitchcock  All rights reserved
;+
;NAME:
;		AX_DISPLAY_PTYCHO
;
;LAST CHANGED: ----------------------------------- 	27 Jul 2015
;
; PURPOSE:
;	This procedure computes and displays the bright field image from a set
; of ptychography images recorded using a Princeton X-ray camera on BVL 11.0.2
; it generates & corrects for camera background  and then displays
; individual ptycho images on a linear or logarithmic scale
; while diplaying a marker on the bright field image.
;
; CATEGORY:
;	stand alone.
;
; CALLING SEQUENCE:
;	AX_DISPLAY_PTYCHO(axis_on=axis_on)
;
; INPUTS: none
;
; KEYWORDS:
;	axis_on	if set, called from aXis (so know to use aXis_ID in parent calls)
;
; INTERNAL ROUTINES
;  FUNCTION AX_CONVERT_UINT_REAL, IMAGE
;			 - convert unsigned 16-bit integers to signed reals
;  FUNCTION AX_PTYCHO_SELECT
; selct the long or short dwell time images for 11.0.2 ptycho measurements
;
; OUTPUTS:
;	No explicit outputs.   A widget is created
; COMMON BLOCKS:
;	AXIS_COM	standard set of common blocks
;	ptycho_com - parameters specific to DISPLAY_PTYCHO
;	AX_SELECT_COM  - parameters for using the
;            'generate mask' widget - the r_mask parameter is used to report the mask
;
; SIDE EFFECTS:
;	A GUI is created/destroyed.
;
; MODIFICATION HISTORY:
; (15-Jan-15 aph) first version
; (27-Jul-15 aph) change display_ptycho_com to ptycho_com (variables with 2 '_' only read 1st 2 of 3 parts of name
;-

; ===============================================
function ax_convert_uint_real, image
; converts unsigned integer (12-bit) arrays to real arrays,
; centers intensity on 0 by adding 2^15, and fixes rollover

; -----------------------------------------------------
; This seems not to be needed - once I used tvscl, not tv, and controlled
; image size, the artifically rolled-over data disappeared . STRANGE
; -----------------------------------------------------

@axis_com
@ptycho_com
	t = size(image)
	r_img=float(image) + 2^15
	tmp=ax_fix_rollover(one=r_img)
	return, tmp
end
; -----------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx  define colors in 1-place !
; -----------------------------------
PRO ptycho_color, stxm=stxm, ptycho=ptycho, first=first, last=last
@axis_com
@ptycho_com
COMMON COLORS, R_orig, G_orig, B_orig, R_curr, G_curr, B_curr

	if keyword_set(first) then begin
		device, decomposed=0
;		help, R_orig, G_orig, B_orig
		TVLCT, ptycho_UserR, ptycho_UserB, ptycho_UserG, /get
		R_orig = ptycho_UserR
		G_orig = ptycho_UserG
		B_orig = ptycho_UserB
	endif

	if keyword_set(last) then begin
		TVLCT, ptycho_UserR, ptycho_UserB, ptycho_UserG
	endif

	if keyword_set(STXM) then begin
		loadct, ColTbl, bottom = 16, ncolors = 256, /silent		; load initial color table for imaging
		ax_color		; setup color scale without loading current color table (not yet set)
	endif
	if	keyword_set(ptycho) then begin
		loadct, 0, /silent
	endif

end
; -----------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -----------------------------------

PRO ax_pause, seconds
; --------- use the system time to execute a pause in units of fractional seconds

now = double(systime(/sec))
finish = now + double(seconds)
while systime(/sec) LT finish do begin
endwhile
return
END

; -----------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -----------------------------------

function ax_ptycho_select,long_short=long_short
; --------- select the long or short dwell time images for 11.0.2 ptycho measurements
@axis_com
@ptycho_com
; -----decide which set of images to process -----------

if not keyword_set(long_short) then begin
	if ptycho_long EQ 1 then long_short= 'long' else long_short= 'short'
endif		; keyword has precedence
; print, 'ptycho_long = ', ptycho_long, '   long_short = ',long_short

; ------ apply to current selection of long (odd) or short acqusition (even) images
	t = ax_name(ptycho_names(0))
	root = t(0)+strmid(t(1), 0, strpos(t(1),'_',/reverse_search))
	ext = t(2)

; ------  generate a list of the file numbers, assuming they are between '_' and '.' in the filename
	num = strarr(n_elements(ptycho_names))
	for i = 0, n_elements(ptycho_names)-1 do begin
	; strip file number from the name
		t = ax_name(ptycho_names(i))
		num (i) = strmid(t(1), strpos(t(1),'_',/reverse_search)+1)
	endfor
	if long_short EQ 'long' then begin		; LONG dwell are ODD file numbers
; -----  identify the odd numbered ones
		odd_num = where((float(num)/2 - floor(num/2)) GT 0., count)
;		print, 'odd_numbers: ', odd_num
		if count gt 0 then begin	; generate an array of the odd numbered files
			ptycho_filename_list = strarr(n_elements(odd_num))
			for i = 0, n_elements(odd_num)-1 do begin
				ptycho_filename_list(i) = root + '_' + strtrim(string(num(odd_num(i))),2) + '.' + ext
			endfor
		endif
	endif else begin					; SHORT dwell are EVEN numbers
		even_num = where((float(num)/2 - floor(num/2)) EQ 0., count)
;		print, 'even_numbers: ', even_num
		if count gt 0 then begin	; generate an array of the even numbered files
			ptycho_filename_list = strarr(n_elements(even_num))
			for i = 0, n_elements(even_num)-1 do begin
				ptycho_filename_list(i) = root + '_' +  num(even_num(i)) + '.' + ext
			endfor
		endif
	endelse
return, ptycho_filename_list

end

;
; -----------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -----------------------------------

pro display_ptycho_event, Event
@axis_com
@ptycho_com
@ax_select_com

on_error,2

; print, 'processing event for button ', Event.ID
  case  Event.ID of
; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -----------  select extended dwell time ptycho images
   display_ptycho_par.extended: BEGIN
	    widget_control, display_ptycho_par.extended, set_button=1
		widget_control, display_ptycho_par.short, set_button=0
		ptycho_long = 1
		print, 'selected: long acquisition images'
    END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -----------  select short dwell time ptycho images
   display_ptycho_par.short: BEGIN
	    widget_control, display_ptycho_par.extended, set_button=0
		widget_control, display_ptycho_par.short, set_button=1
		ptycho_long = 0
		print, 'selected: short acquisition images'
    END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; ------------ edit # X-pixels
	display_ptycho_par.x_pixels: BEGIN
		widget_control, display_ptycho_par.x_pixels, get_value=text
		x_pixels = fix(text)  &  t = x_pixels(0) & x_pixels = t
		print, '#  X pixels changed to ', x_pixels
    END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; ------------ edit # Y-pixels
	display_ptycho_par.y_pixels: BEGIN
		widget_control, display_ptycho_par.y_pixels, get_value=text
		y_pixels = fix(text) &  t = y_pixels(0) & y_pixels = t
		print, '#  Y pixels changed to ', y_pixels
    END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; ---------- edit pixel size
	display_ptycho_par.pixel_size: BEGIN
		widget_control, display_ptycho_par.pixel_size, get_value=text
		pixel_size = float(text)
		print, 'pixel size changed to ', pixel_size
   END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; --------------- select specific x-pixel  and plot corresponding diffraction image
	display_ptycho_par.x_pixel_num: BEGIN
		widget_control, display_ptycho_par.x_pixel_num, get_value=text
		ptycho_xy_num(0) = fix(text)
; load corresponding ptycho_image if data defined
		if n_elements(ptycho_filename_list) NE 0 then begin
			ptycho_img = ptycho_xy_num(1)*x_pixels + ptycho_xy_num(0)
			tmp = read_tiff(ptycho_filename_list(ptycho_img))
			t=size(tmp)
			if ptycho_sub AND n_elements(ptycho_bgnd) GT 0 then $
					    bgnd = ptycho_bgnd else bgnd = 0.*tmp
			wset, display_ptycho_par.ptycho_image_win
			if ptycho_log EQ 1 then tvscl, alog10(rebin((tmp - bgnd),t(1)/2,t(2)/2)) else $
			      tvscl, rebin((tmp - bgnd),t(1)/2,t(2)/2)
		endif
	END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; --------------- select specific y-pixel and plot corresponding diffraction image
	display_ptycho_par.y_pixel_num: BEGIN
		widget_control, display_ptycho_par.y_pixel_num, get_value=text
		ptycho_xy_num(1) = fix(text)
; load corresponding ptycho_image if data defined
		if n_elements(ptycho_filename_list) NE 0 then begin
			ptycho_img = ptycho_xy_num(1)*x_pixels + ptycho_xy_num(0)
			tmp = read_tiff(ptycho_filename_list(ptycho_img))
			t=size(tmp)
			if ptycho_sub AND n_elements(ptycho_bgnd) GT 0 then $
					    bgnd = ptycho_bgnd else bgnd = 0.*tmp
			wset, display_ptycho_par.ptycho_image_win
			if ptycho_log EQ 1 then tvscl, alog10(rebin((tmp - bgnd),t(1)/2,t(2)/2)) else $
			      tvscl, rebin((tmp - bgnd),t(1)/2,t(2)/2)
		endif
	END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -------- switch to log (base 10) display of ptycho image
	display_ptycho_par.log : BEGIN
		widget_control, display_ptycho_par.log, set_button=1
		widget_control, display_ptycho_par.linear, set_button=0
		ptycho_log = 1
   END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -------- switch to linear display of ptycho image
	display_ptycho_par.linear : BEGIN
		widget_control, display_ptycho_par.log, set_button=0
		widget_control, display_ptycho_par.linear, set_button=01
		ptycho_log = 0
   END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -------- switch to subtract background
	display_ptycho_par.Subtract_Background : BEGIN
		test = fix(ptycho_sub)
		widget_control, display_ptycho_par.Subtract_Background, set_button=1
		widget_control, display_ptycho_par.all_signal, set_button=0
		ptycho_sub = 1 & axis_log, 'background (if evaluated) will be subtracted'
	END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -------- switch to display signal & background
	display_ptycho_par.all_signal : BEGIN
	widget_control, display_ptycho_par.Subtract_Background, set_button=0
	widget_control, display_ptycho_par.all_signal, set_button=1
	ptycho_sub = 0 & axis_log, 'background will NOT be subtracted'
	END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -------- edit the playback rate
	display_ptycho_par.rate: BEGIN
	widget_control, display_ptycho_par.rate, get_value=text
	ptycho_rate = fix(text)
	print, 'playback rate changed to ' + string(ptycho_rate*0.05,format='(F5.2)') + ' seconds/image'
 	END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -----------  load STXM (or bright field ptycho) image
   display_ptycho_par.Load_Bright_Field: BEGIN
  		ptycho_bf = axb_load(title='Select Bright Field image (STXM equivalent)')
		wset, display_ptycho_par.STXM_image_win
		ptycho_color, /stxm
		splot2d,  ptycho_bf
  		bf_loaded = 1
  		ptycho_STXM_plot = !p
  		widget_control, display_ptycho_par.STXM_image, sensitive=1
    END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -----------  load bright field MASK
   display_ptycho_par.Load_Mask: BEGIN
  		tmp = axb_load(title='Select bright field Mask')
  		ptycho_mask = tmp.d
		wset, display_ptycho_par.ptycho_image_win
		erase
		ptycho_color, /ptycho
		t=size(ptycho_mask)
		tvscl, rebin((ptycho_mask),t(1)/2,t(2)/2)
    END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -----------  load background
   display_ptycho_par.Load_background: BEGIN
  		tmp = axb_load(title='Select background image')
  		ptycho_bgnd = tmp.d
		wset, display_ptycho_par.ptycho_image_win
		erase
		ptycho_color, /ptycho
		t=size(ptycho_bgnd)
		tvscl, rebin((ptycho_bgnd),t(1)/2,t(2)/2)
    END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; ----------- generate background from average of images recorded with shutter closed
	display_ptycho_par.generate_background: BEGIN
		bgnd_names = dialog_pickfile(title = 'Please select all background images', $
	              filter='*.tif', /multiple_files)
	    t = ax_name(bgnd_names(0))
		fileshort = strmid(t(1), 0, strpos(t(1),'_',/reverse_search))
		root = t(0) + fileshort
		widget_control, display_ptycho_par.background_folder, set_value=root
	    image=double(read_tiff(bgnd_names(0)))
	    for i = 1, n_elements(bgnd_names) - 1 do begin
	    	image=image + double(read_tiff(bgnd_names(i)))
	    endfor
	    ptycho_bgnd = float(image/n_elements(bgnd_names))
; ----  display on display_ptycho panel
		wset, display_ptycho_par.ptycho_image_win
		ptycho_color, /ptycho
		t = size(ptycho_bgnd)
		tvscl, alog10(rebin(ptycho_bgnd,t(1)/2,t(2)/2))
; ---- save the background image
		x = findgen(t(1))
		y = findgen(t(2))
		if n_elements(ptycho_e) EQ 0 then begin
			if from_axis then $
		          ptycho_E = get_num(title='Define photon energy', $
		          prompt='photon energy',val=ptycho_E, group=aXis_ID) $
		    else ptycho_E = get_num(title='Define photon energy', $
		          prompt='photon energy',val=ptycho_E, group= display_ptycho_par.STXM_image)
		endif
		tmp = {t:'2d', x:x, y:y, xl:'x (pixels)', yl:'y (pixel)', $
		        e: ptycho_e, d: ptycho_bgnd, dl:fileshort +  ' background image'}
		t = AXB_SAVE(tmp, /no_axis)
	END


; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; ----------- generate Bright Field image from the ptycho data
   display_ptycho_par.Generate_Bright_Field: BEGIN

; collect names of all the *.tif files in the ptycho folder if not yet obtained
		if n_elements(ptycho_names) EQ 0 then begin
			ptycho_names = dialog_pickfile(title = 'Please select all ptycho images', $
			              filter='*.tif', /multiple_files)
		endif
		t = ax_name(ptycho_names(0))
		fileshort = strmid(t(1), 0, strpos(t(1),'_',/reverse_search))
		root = t(0) + fileshort
		ext = t(2)
; --------- generate bright field mask using threshold masking
		If n_elements(ptycho_mask) EQ 0 then begin
; --------  load first tif image
			first_image = read_tiff(ptycho_names(0))
			 ax_select,tiff=first_image, no_axis=1, GROUP_LEADER=display_ptycho_par.main_base
; --------- mask is passed through ax_select_com  (as the variable, r_mask)
			ptycho_mask=r_mask
		endif

; ------  select  short acqusition (even) images
;       - the bright field in the long ones is absorption saturated
		ptycho_filename_list = ax_ptycho_select(long_short='short')

; ------ apply mask to all files to generate the bright field image
		i = 0
		bright_field=fltarr(x_pixels, y_pixels)
		for j = 0, y_pixels-1 do begin
			for k = 0, x_pixels-1 do begin
				file = ptycho_filename_list(i)
				img=read_tiff(file)
				r_img = ptycho_mask*float(img)
				nz = where(r_img NE 0, count)
				if count NE 0 then bright_field(k,j) = mean(r_img(nz)) else bright_field(k,j) = 0
;				print, i, ' processing ', file , k, j, bright_field(k,j)
				i = i + 1
			endfor
		endfor

; ---- save the bright field image
		x = findgen(x_pixels)*pixel_size
		y = findgen(y_pixels)*pixel_size
		if from_axis then $
		ptycho_E = get_num(title='Define photon energy', $
		          prompt='photon energy',val=ptycho_E, group=aXis_ID) $
		   else ptycho_E = get_num(title='Define photon energy', $
		          prompt='photon energy',val=ptycho_E, group= display_ptycho_par.STXM_image)
		ptycho_bf = {t:'2d', x:x, y:y, xl:'x (um)', yl:'y (um)', e: ptycho_E, $
		       d: bright_field, dl:fileshort + ' bright-field image'}
		t = AXB_SAVE(ptycho_bf, /no_axis)
		bf_loaded = 1

; -------- display the bright field image
		wset, display_ptycho_par.STXM_image_win
		ptycho_color, /stxm
		splot2d,  ptycho_bf
  		ptycho_STXM_plot = !p
  		widget_control, display_ptycho_par.STXM_image, sensitive=1
	END


; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; ----- play ptycho images while highlighting the pixel in the bright field image
  display_ptycho_par.Play: BEGIN
; check if bright field loaded - if not prompt
	if bf_loaded NE 1 then begin
  		tmp = axb_load(title='Select Bright Field image (STXM equivalent)')
		wset, display_ptycho_par.STXM_image_win
		ptycho_color, /ptycho
		t = size(tmp.d)
		splot2d,  tmp
  		bf_loaded = 1
  		ptycho_STXM_plot = !p
  		widget_control, display_ptycho_par.STXM_image, sensitive=1
	endif
; collect names of all the *.tif files in the ptycho folder if not yet obtained
	if n_elements(ptycho_names) EQ 0 then begin
		ptycho_names = dialog_pickfile(title = 'Please select all ptycho images', $
		              filter='*.tif', /multiple_files)
	endif
	ptycho_filename_list = ax_ptycho_select()
; read and display
	n_img = n_elements(ptycho_filename_list)
	wset, display_ptycho_par.ptycho_image_win
	ptycho_diffract_plot = !p
	j = 0 & k = 0
	print, 'Reading in first ptycho image file ', ptycho_filename_list(0)
	tmp = read_tiff(ptycho_filename_list(0))
	if ptycho_sub AND n_elements(ptycho_bgnd) GT 0 then bgnd = ptycho_bgnd else bgnd = 0.*tmp
	zoom = ptycho_zoom*3.6	; kluge to see if this tuned scale factor will get pixels correctly located    ;
	xfact = 0.95
	for i = 0, n_img-1 DO BEGIN
		tmp = read_tiff(ptycho_filename_list(i))
		t=size(tmp)
		if ptycho_log EQ 1 then tvscl, alog10(rebin((tmp - bgnd),t(1)/2,t(2)/2)) else $
		      tvscl, rebin((tmp - bgnd),t(1)/2,t(2)/2)
; ------ add pixel indicator on the STXM image
;		wset, display_ptycho_par.STXM_image_win
;		!p = ptycho_STXM_plot
;		device, get_graphics_function = oldgraph, set_graphics_function = 6      ;Set xor
;		ptycho_color, /stxm

;		xlo = j*zoom*xfact &  xhi = (j+1)*zoom*xfact
;		ylo = (y_pixels-k)*zoom &  yhi = (y_pixels-k-1)*zoom
;		oplot, [xlo,xhi], [ylo,yhi], psym=6, thick=2, color = ax_blue_color_index
; ------ display pixel number and wait
		widget_control, display_ptycho_par.x_pixel_num, set_value = string(j+1)
		widget_control, display_ptycho_par.y_pixel_num, set_value = string(k+1)
;		print, j, k
		j = j + 1
		if j GT x_pixels - 1 then j = 0
		if j EQ 0 then k = k + 1
		ax_pause, ptycho_rate*0.05
; ------ erase the symbol indicating location of last diffraction image
;		device, set_graphics_function = oldgraph   ; reset graphics mode
;		wset, display_ptycho_par.ptycho_image_win	; return plot window to diffraction image
;		!p = ptycho_diffract_plot
;		ptycho_color, /ptycho
	endfor
  END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; ------------------- process a click on the bright field image display
   display_ptycho_par.STXM_image: BEGIN
   	if event.press EQ 1 then begin 	; only process on press, not release
   		wset, display_ptycho_par.STXM_image_win
   		ptycho_color, /stxm
		curval = CONVERT_COORD(Event.X, Event.Y, /DEVICE, /TO_DATA)
;		print, 'cursor at ', curval
;		help, ptycho_Bf, /struct
		CurInd = DIndex(curval(0),curval(1),ptycho_bf)
		ptycho_xy_num(0) = fix(CurInd(0)) & ptycho_xy_num(1) = fix(CurInd(1))
;		print, 'user selected pixel ', ptycho_xy_num(0), ptycho_xy_num(1)
		widget_control, display_ptycho_par.x_pixel_num, set_value=string(fix(ptycho_xy_num(0)))
		widget_control, display_ptycho_par.y_pixel_num, set_value=string(fix(ptycho_xy_num(1)))
; ------- erase last indicator if there is one
;		if n_elements(oldgraph) then begin
;			device, set_graphics_function = oldgraph   ; reset graphics mode
;			oplot, [xlo,xhi], [ylo,yhi], psym=6, thick=1, color = 0
;		endif
; -------------- indicate point on the bright field image
;		device, get_graphics_function = oldgraph, set_graphics_function = 6      ;Set xor
;		xlo = curval(0)  & xhi = curval(0)+1
;		ylo = curval(1)  & yhi = curval(1)+1
;		oplot, [xlo,xhi], [ylo,yhi], psym=6, thick=1 , color = 0
; load corresponding ptycho_image if data defined
		if n_elements(ptycho_filename_list) NE 0 then begin
			ptycho_img = ptycho_xy_num(1)*x_pixels + ptycho_xy_num(0)
			tmp = read_tiff(ptycho_filename_list(ptycho_img))
			t=size(tmp)
			if ptycho_sub AND n_elements(ptycho_bgnd) GT 0 then $
					    bgnd = ptycho_bgnd else bgnd = 0.*tmp
			wset, display_ptycho_par.ptycho_image_win
			!p = ptycho_diffract_plot
			ptycho_color, /ptycho
			if ptycho_log EQ 1 then tvscl, alog10(rebin((tmp - bgnd),t(1)/2,t(2)/2)) else $
			      tvscl, rebin((tmp - bgnd),t(1)/2,t(2)/2)
		endif
	 endif
   END

; --------------------------------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; ----------- dismiss the widget
   display_ptycho_par.Dismiss: BEGIN
        widget_control,display_ptycho_par.main_base,/destroy
        ptycho_color, /last
;        TVLCT, ptycho_UserR, ptycho_UserB, ptycho_UserG
;        !p = initial_colors
    END

    else:
  endcase

end

;
; -----------------------------------
; xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
; -----------------------------------


pro ax_display_ptycho, axis_on=axis_on
@axis_com
@ptycho_com

; ------- determine folder with ptycho images
ptycho_1 = pickfile2(title='Select any tif file in the folder with the ptycho images', $
         FILTER='*.tif', /LPATH, DEFPATH=defpath)
ptycho_folder = lpath
; ---- read names of all tif files in the ptycho folder -------
;if n_elements(ptycho_names) EQ 0 then ptycho_names = ' '
;ptycho_names = dialog_pickfile(filter = '*.tif',/multiple_files, get_path = ptycho_folder, $
;         title = "Select all tif files in the folder with the ptycho images")
; t=ax_name(ptycho_names(0))
; ptycho_folder = t(0)
lpath =  ptycho_folder
defpath =  ptycho_folder
cd,  ptycho_folder
print, 'ptycho image folder ', ptycho_folder
t = ax_name(ptycho_1)
ptycho_fileshort = strmid(t(1), 0, strpos(t(1),'_',/reverse_search))
ptycho_root = t(0) + ptycho_fileshort
ptycho_ext = t(2)


; define parameters
IF (n_tags(display_ptycho_par) EQ 0) THEN BEGIN
    display_ptycho_par = $
      { display_ptycho_par, $
        main_base: 0L, $
        ptycho_folder: 0L, $
        background_folder:  0L, $
        Generate_Bright_Field: 0L, $
        Load_Bright_Field: 0L, $
        Load_Mask:  0L, $
        generate_background: 0L, $
        Load_background: 0L, $
        subtract_background: 0L, $
        all_signal:  0L, $
        log_linear: 0L, $
        ptycho_image: 0L, $
        ptycho_image_win: 0L, $
        STXM_image: 0L, $
        STXM_image_win: 0L, $
        extended: 0L, $
        short: 0L, $
        x_pixels: 0L, $
        y_pixels: 0L, $
        pixel_size: 0L, $
        x_pixel_num: 0L, $
        y_pixel_num: 0L, $
        log: 0L, $
        linear: 0L, $
        rate: 0L, $
        play: 0L, $
        stop: 0L, $
        folder: 0L, $
        dismiss: 0L $
      }
ENDIF

if n_elements(ptycho_folder) GT 0 then ptycho_data_folder = ptycho_folder		; since ptycho_folder is in the call, cannot pass in by common


; ---------- make sure have parameters to define correct bright field image window
if n_elements(x_pixels) EQ 0 then x_pixels = 20
if n_elements(y_pixels) EQ 0 then y_pixels = 10
if n_elements(pixel_size) EQ 0 then pixel_size = 50.
if n_elements(ptycho_zoom) EQ 0 then ptycho_zoom = 20
if keyword_set(axis_on) then begin
	from_axis = 1
	x_pixels = get_num(title='ax_display_ptycho: parameters', prompt='# of X-pixels',val=x_pixels, group = AXIS_ID)
	y_pixels = get_num(title='ax_display_ptycho: parameters',prompt='# of Y-pixels',val=y_pixels, group = AXIS_ID)
	pixel_size = get_num(title='ax_display_ptycho: parameters',prompt='pixel size (nm)',val=pixel_size, group = AXIS_ID)
	ptycho_zoom = get_num(title='ax_display_ptycho: parameters',prompt='Zoom factor for bright field display', $
	            val=ptycho_zoom, group = AXIS_ID)
endif else begin
	from_axis = 0
	x_pixels = get_num(title='ax_display_ptycho: parameters', prompt='# of X-pixels',val=x_pixels)
	y_pixels = get_num(title='ax_display_ptycho: parameters',prompt='# of Y-pixels',val=y_pixels)
	pixel_size = get_num(title='ax_display_ptycho: parameters',prompt='pixel size (nm)',val=pixel_size)
	ptycho_zoom = get_num(title='ax_display_ptycho: parameters',prompt='Zoom factor for bright field display', $
	            val=ptycho_zoom)
endelse

if (ptycho_zoom*x_pixels) GT 640 then main_x_size = ptycho_zoom*x_pixels else main_x_size = 640
 main_y_size = ptycho_zoom*y_pixels + 360

; ------------ generate widget content

  display_ptycho_par.main_base = Widget_Base( $
       Title ='Display Ptychography Images', UNAME='Display Ptycho'  $
      ,XOFFSET=5 ,YOFFSET=5 ,SCR_XSIZE=main_x_size ,SCR_YSIZE=main_y_size,SPACE=3 ,XPAD=3 ,YPAD=3)

  display_ptycho_par.ptycho_image = Widget_Draw(display_ptycho_par.main_base, UNAME='ptycho_image' ,XOFFSET=32  $
      ,YOFFSET=62 ,SCR_XSIZE=250 ,SCR_YSIZE=250, retain=2)

  display_ptycho_par.STXM_image = Widget_Draw(display_ptycho_par.main_base, UNAME='STXM_image' ,XOFFSET=5  $
      ,YOFFSET=330 ,SCR_XSIZE=ptycho_zoom*x_pixels ,SCR_YSIZE=ptycho_zoom*y_pixels, $
      retain=2, /button_events, sensitive=0)

  WID_LABEL_0 = Widget_Label(display_ptycho_par.main_base, UNAME='WID_LABEL_0'  $
      ,XOFFSET=41 ,SCR_XSIZE=70 ,SCR_YSIZE=18 ,/ALIGN_LEFT, VALUE='Ptycho folder')
  display_ptycho_par.ptycho_folder = Widget_Text(display_ptycho_par.main_base, UNAME='ptycho folder'  $
      ,XOFFSET=116,SCR_YSIZE=21,YSIZE=1, XSIZE=75)

  WID_LABEL_1 = Widget_Label(display_ptycho_par.main_base, UNAME='WID_LABEL_1'  $
      ,XOFFSET=41 ,YOFFSET = 28, SCR_XSIZE=70 ,SCR_YSIZE=18 ,/ALIGN_LEFT, VALUE='Background folder')
  display_ptycho_par.background_folder = Widget_Text(display_ptycho_par.main_base, UNAME='Background '  $
      ,XOFFSET=116,YOFFSET = 28, SCR_YSIZE=21,YSIZE=1, XSIZE=75)

; make a container for all of the parameter and buttons so they can all be moved together

  WID_BASE_1 = Widget_Base(display_ptycho_par.main_base, UNAME='WID_BASE_1'  $
      ,XOFFSET=300 ,YOFFSET=66 ,SCR_XSIZE=340 ,SCR_YSIZE=280,SPACE=3 ,XPAD=3 ,YPAD=3)

  display_ptycho_par.Generate_Bright_Field = Widget_Button(WID_BASE_1, UNAME='Generate_Bright_Field'  $
      ,XOFFSET=2 ,YOFFSET=0 ,SCR_XSIZE=120 ,SCR_YSIZE=32  $
      ,/ALIGN_CENTER ,VALUE='Generate Bright Field')

  display_ptycho_par.Load_Bright_Field = Widget_Button(WID_BASE_1, UNAME='LoadBright_Field'  $
      ,XOFFSET=152 ,YOFFSET=0 ,SCR_XSIZE=120 ,SCR_YSIZE=32  $
      ,/ALIGN_CENTER ,VALUE='Load Bright Field')

  display_ptycho_par.Generate_background = Widget_Button(WID_BASE_1,  $
      UNAME='Subtract_background' ,XOFFSET=2 ,YOFFSET=38  $
      ,SCR_XSIZE=100 ,SCR_YSIZE=32 ,/ALIGN_CENTER ,VALUE='Generate Bgnd')
  display_ptycho_par.Load_background = Widget_Button(WID_BASE_1,  $
      UNAME=' Load background' ,XOFFSET=106 ,YOFFSET=38  $
      ,SCR_XSIZE=80 ,SCR_YSIZE=32 ,/ALIGN_CENTER ,VALUE='Load Bgnd')
  display_ptycho_par.Load_Mask = Widget_Button(WID_BASE_1,  $
      UNAME='Load Mask' ,XOFFSET=194 ,YOFFSET=38  $
      ,SCR_XSIZE=80 ,SCR_YSIZE=32 ,/ALIGN_CENTER ,VALUE='Load Mask')

  WID_BASE_6 = Widget_Base(WID_BASE_1, UNAME='WID_BASE_6'  $
      ,XOFFSET=15 ,YOFFSET=70 ,COLUMN=1 ,/EXCLUSIVE)
  display_ptycho_par.Subtract_Background = Widget_Button(WID_BASE_6, $
      VALUE='Subtract background', UNAME='subtract background' ,/ALIGN_LEFT)
  WID_BASE_7 = Widget_Base(WID_BASE_1, UNAME='WID_BASE_6'  $
      ,XOFFSET=15 ,YOFFSET=90 ,COLUMN=1 ,/EXCLUSIVE)
  display_ptycho_par.all_signal = Widget_Button(WID_BASE_7, $
      VALUE='Signal + background', UNAME='signal + background' ,/ALIGN_LEFT)

  WID_BASE_2 = Widget_Base(WID_BASE_1, UNAME='WID_BASE_2'  $
      ,XOFFSET=166 ,YOFFSET=70 ,TITLE='IDL' ,COLUMN=1 ,/EXCLUSIVE)
  display_ptycho_par.extended = Widget_Button(WID_BASE_2, UNAME='Long' ,/ALIGN_LEFT  $
      ,VALUE='long (150 ms)')

  WID_BASE_3 = Widget_Base(WID_BASE_1, UNAME='WID_BASE_3'  $
      ,XOFFSET=166 ,YOFFSET=90 ,TITLE='IDL' ,COLUMN=1 ,/EXCLUSIVE)
  display_ptycho_par.short = Widget_Button(WID_BASE_3, UNAME='short' ,/ALIGN_LEFT  $
      ,VALUE='short (15 ms)')

  LABEL_x_pixels = Widget_Label(WID_BASE_1, UNAME='LABEL_x_pixels'  $
      ,XOFFSET=156 ,YOFFSET=130 ,/ALIGN_LEFT ,VALUE='# X pixels')
  display_ptycho_par.x_pixels = Widget_Text(WID_BASE_1, UNAME='X_pixels', /EDITABLE  $
      , XOFFSET=212 ,YOFFSET=130 ,SCR_XSIZE=50, XSIZE=20, YSIZE=1)

  LABEL_y_pixels = Widget_Label(WID_BASE_1, UNAME='LABEL_y_pixels'  $
      ,XOFFSET=155 ,YOFFSET=157 ,/ALIGN_LEFT ,VALUE='# Y pixels')
   display_ptycho_par.y_pixels = Widget_Text(WID_BASE_1, UNAME='Y_pixels', /EDITABLE  $
      , XOFFSET=212 ,YOFFSET=157 ,SCR_XSIZE=50, YSIZE=1, XSIZE=20)

  LABEL_pixel_size = Widget_Label(WID_BASE_1, UNAME='LABEL_pixel_size'  $
      ,XOFFSET=156 ,YOFFSET=182 ,/ALIGN_LEFT ,VALUE='pixel_size')
   display_ptycho_par.pixel_size = Widget_Text(WID_BASE_1, UNAME='pixel_size', /EDITABLE  $
      , XOFFSET=212 ,YOFFSET=182 ,SCR_XSIZE=50 ,SCR_YSIZE=19 ,XSIZE=20, YSIZE=1)

 WID_BASE_4 = Widget_Base(WID_BASE_1, UNAME='WID_BASE_4'  $
      ,XOFFSET=16 ,YOFFSET=182 ,COLUMN=1 ,/EXCLUSIVE)
  display_ptycho_par.log = Widget_Button(WID_BASE_4, UNAME='log' ,/ALIGN_LEFT  $
      , SCR_YSIZE=15, VALUE='log')
  WID_BASE_5 = Widget_Base(WID_BASE_1, UNAME='WID_BASE_5'  $
      ,XOFFSET=70 ,YOFFSET=182 ,COLUMN=1 ,/EXCLUSIVE)
  display_ptycho_par.linear = Widget_Button(WID_BASE_5, UNAME='linear' ,/ALIGN_LEFT  $
      ,SCR_YSIZE=15, VALUE='linear')

  LABEL_x_pixel_num = Widget_Label(WID_BASE_1, UNAME='LABEL_x_pixel_num'  $
      ,XOFFSET=16 ,YOFFSET=134 ,/ALIGN_LEFT ,VALUE='X pixel')
   display_ptycho_par.x_pixel_num = Widget_Text(WID_BASE_1, UNAME='x_pixel_num', /EDITABLE  $
      , XOFFSET=56 ,YOFFSET=130 , XSIZE=5, YSIZE=1, VALUE='0')

  LABEL_y_pixel_num = Widget_Label(WID_BASE_1, UNAME='LABEL_x_pixel_num'  $
      ,XOFFSET=16 ,YOFFSET=161 ,/ALIGN_LEFT ,VALUE=' Y pixel')
   display_ptycho_par.y_pixel_num = Widget_Text(WID_BASE_1, UNAME='y_pixel_num', /EDITABLE  $
      , XOFFSET=56 ,YOFFSET=157 , XSIZE=5, YSIZE=1, VALUE='0')

  display_ptycho_par.Play = Widget_Button(WID_BASE_1, UNAME='Play' ,XOFFSET=16  $
      ,YOFFSET=220 ,SCR_XSIZE=65 ,SCR_YSIZE=35 ,/ALIGN_CENTER,  VALUE='Play')

  LABEL_rate = Widget_Label(WID_BASE_1, UNAME='rate_label'  $
      ,XOFFSET=90 ,YOFFSET=210 ,/ALIGN_LEFT ,VALUE='rate (multiples of 50 ms)')
   display_ptycho_par.rate = Widget_Text(WID_BASE_1, UNAME='rate', /EDITABLE  $
      , XOFFSET=120 ,YOFFSET=230 , XSIZE=5, YSIZE=1, VALUE='2')

;  display_ptycho_par.Stop = Widget_Button(WID_BASE_1, UNAME='Stop' ,XOFFSET=88  $
;      ,YOFFSET=210 ,SCR_XSIZE=65 ,SCR_YSIZE=35 ,/ALIGN_CENTER ,VALUE='Stop')

  display_ptycho_par.Dismiss = Widget_Button(WID_BASE_1, UNAME='Dismiss' ,XOFFSET=200  $
      ,YOFFSET=220 ,SCR_XSIZE=65 ,SCR_YSIZE=35 ,/ALIGN_CENTER,VALUE='Dismiss')

widget_control, display_ptycho_par.main_base, /realize

;------- set defaults
ptycho_long = 1
widget_control, display_ptycho_par.extended, set_button=1
widget_control, display_ptycho_par.short, set_button=0
widget_control, display_ptycho_par.ptycho_folder, set_VALUE=ptycho_folder
ptycho_sub = 1
widget_control, display_ptycho_par.Subtract_background, set_button=1

widget_control, display_ptycho_par.x_pixels, set_value=string(fix(x_pixels))
widget_control, display_ptycho_par.y_pixels, set_value=string(fix(y_pixels))
widget_control, display_ptycho_par.pixel_size, set_value=string(pixel_size, format='(F5.1)')
bf_loaded = 0
widget_control, display_ptycho_par.log, set_button=1
ptycho_log = 1
ptycho_xy_num = [0,0]
if n_elements(ptycho_rate) EQ 0 then ptycho_rate = 2   ; default play back is 10 ptycho images/sec
widget_control, display_ptycho_par.rate, set_value=string(ptycho_rate)

; ------ get window numbers for the ptycho_image draw windows to use later
widget_control,display_ptycho_par.ptycho_image,get_value=window
display_ptycho_par.ptycho_image_win = window
; print, 'display_ptycho_par.ptycho_image_win = ' , display_ptycho_par.ptycho_image_win
widget_control,display_ptycho_par.STXM_image,get_value=window
display_ptycho_par.STXM_image_win = window
; print, 'display_ptycho_par.STXM_image_win = ' , display_ptycho_par.STXM_image_win

if not keyword_set(axis_on) then aXis_ID =  display_ptycho_par.main_base  ; kluge during stand-alone to avoid modal no-group problem


; ------ grab present color table to be able to replace after dismiss this widget
 initial_colors = !p
TVLCT, ptycho_UserR, ptycho_UserB, ptycho_UserG, /get	; grab existing color palette to restore

;------------- display the ptycho_1 image
tmp = read_tiff(ptycho_1)
t=size(tmp)
if  n_elements(ptycho_bgnd) GT 0 then bgnd = ptycho_bgnd else bgnd = 0.*tmp
wset, display_ptycho_par.ptycho_image_win
ptycho_color, /first
ptycho_color, /ptycho
if ptycho_log EQ 1 then tvscl, alog10(rebin((tmp - bgnd),t(1)/2,t(2)/2)) else $
      tvscl, rebin((tmp - bgnd),t(1)/2,t(2)/2)
ptycho_diffract_plot = !p

xmanager, 'display_ptycho', display_ptycho_par.main_base, $
  group_leader = display_ptycho_par.main_base

return
end
