; Copyright (c) 1998-2009 A.P. Hitchcock & Remy Coulombe  All rights reserved
;
;------This section was added on 7 July 2006 by Remy Coulombe, contact me for info
;remi.coulombe@ma.cgocable.ca/tabarmyside@gmail.com; R.C.
;many of the routine are adaptation of the ones created by the previous programmer
;
;+
;NAME:
;		REGION_ANALYZE
;
;LAST CHANGED: ----------------------------------- 	(13-apr-08) (from 03-Mar-08 (MJ)
;
; PURPOSE:
;	This set of procedures is a widget which allows the use to group regions
; in an image set (stack) based on spectral response. It was developed for use
; with energy filtered PEEM stacks in whch the photoelectron spectrum defines the chemistry
; The user selects multiple (up to 10) spectral signals from a display of the average spectrum
; and the code identifies regions strong in each signal, and presents the reuslts to the user as a map
;
; CATEGORY:
;	Image analysis - called from aXis2000, via Rstack_Analyse
;
; CALLING SEQUENCE:
; 	REGION_ANALYZE
;
; INPUTS:
; all inputs are obtained via common form the parent code
;
; KEYWORDS: none
;
; OUTPUTS:
;
; CONTENTS:
;	region_analyze_imgdisp 		stack image display
;	region_analyze_result_disp	display resulting image (colorized)
;	region_analyze_maximg		detects maximum position
;	region_analyze_event		event processing codes
;	region_analyze_sav_bin_test	math check
;	region_analyze_def_reg		define regions (no code)
;	region_analyze_remove_reg	remove last region
;	region_analyze_reset_reg	remove all regions
;	region_analyze_desensitive	desensitize non-useful buttons
;	region_analyze_sensitive	sensitize buttons
;	region_analyze_save			save the image of the identified regions
;
;
; COMMON BLOCKS:
;	region_analyze_common
;	axis_com
;	bsif_com
;	stack_process_com

;
; SIDE EFFECTS:
;	A window is created/destroyed.
;
; RESTRICTIONS:
;	Any known ?
;
; PROCEDURE:
;	details where needed
;
; MODIFICATION HISTORY:
; (18-Aug-06 rec) code provided to APH for incorporation in axis2000
; (22-Sep-06 aph) AXIS standard header added; some docs added
; (03-Mar-08 MJ)  keyword /SCROLL in widget_base() needs X_SCROLL_SIZE
; (13-apr-08 aph) turn on pre-set window size (X_Scroll_size, Y_Scroll_size) only for non-Windows
; (30-jul-09 aph) changed analcom to stack_process_com (update to stack_process)
;
;-

; ----------stack image display routine
PRO region_analyze_imgdisp, i_file, _extra = e
@axis_com
@bsif_com
@stack_process_com
@region_analyze_common
COMMON volume_data, image_stack

wset,region_analyze_par.image_win
tv,bytarr(n_cols/2,textregion_ypix),0,0,/device

;graph setup
step_x = (x_stop - x_start)/float(n_cols)
ixl = floor(0.5 + (disp_xmin - x_start)/step_x)
if ixl lt 0 then ixl = 0
ixh = floor(0.5 + (disp_xmax - x_start)/step_x)
if ixh gt n_cols-1 then ixh = fix(n_cols-1)
step_y = (y_stop - y_start)/float(n_rows)
iyl = floor(0.5 + (disp_ymin - y_start)/step_y)
if iyl lt 0 then iyl = 0
iyh = floor(.5 + (disp_ymax - y_start)/step_y)
if iyh gt n_rows-1 then iyh = fix(n_rows-1)
; extract portion of image within these indices
tmp_dat =  image_stack(ixl:ixh,iyl:iyh,i_file)
tmp_min = disp_min
tmp_max = disp_max
test = where(i0_signal GT 0,count)

; (aph 30-jun-98) - allow convert to OD
if OD_flag EQ 1 AND count GT 0 then begin
	tmp_i0 = i0_signal(i_file)
    if tmp_i0 LE 0 then i0_signal(i_file) = 1.
 	tmp_dat = -alog(image_stack(*,*,i_file)/i0_signal(i_file))
endif

if rescale_flag EQ 1 then begin
	tmp_min=0
	tmp_max = 255
	tmp_dat = bytscl(tmp_dat)
endif

byte_image = byte(0.5+float(top_color_index)* $
                  (( (((tmp_dat-tmp_min) / $
                       float(tmp_max-tmp_min))^disp_gamma) $
                     >0.)<1.))<byte(top_color_index)
i_svec = size(i_roi)
i0_svec = size(i0_roi)

IF (i_svec(0) NE 0) THEN BEGIN
; convert i_roi to the zoomed image scale
	t = make_array(n_cols,n_rows,/integer,value = 0)		; set up array with i_roi
	t(i_roi) = 1
	tt =  t(ixl:ixh,iyl:iyh)		; select out part that is in displayed region
	i_roi_zoom = where(tt EQ 1)
	all_img_indices = where(byte_image)
	all_img_min = min(all_img_indices, max = all_img_max)
	ttt = where(i_roi_zoom GE all_img_min AND i_roi_zoom LE all_img_max, count)
	if count GT 0 then begin
		i_roi_zoom_indices = i_roi_zoom(ttt)
     	byte_image(i_roi_zoom_indices) = i_color_index
    endif
ENDIF
IF (i0_svec(0) NE 0) THEN BEGIN
; convert i0_roi to the zoomed image scale
	t = make_array(n_cols,n_rows,/integer,value = 0)		; set up array with i0_roi
	t(i0_roi) = 1
	tt =  t(ixl:ixh,iyl:iyh)		; select out part that is in displayed region
	i0_roi_zoom = where(tt EQ 1)
	all_img_indices = where(byte_image)
	all_img_min = min(all_img_indices, max = all_img_max)
	ttt = where(i0_roi_zoom GE all_img_min AND i0_roi_zoom LE all_img_max, count)
	if count GT 0 then begin
		i0_roi_zoom_indices = i0_roi_zoom(ttt)
        byte_image(i0_roi_zoom_indices) = i0_color_index
    endif
ENDIF

wset,region_analyze_par.image_win   ; force back to image display

test_disp_dimension=size(byte_image)
if test_disp_dimension(0) EQ 2 then begin
 tv,congrid(byte_image,n_cols/2,n_rows/2), $      ; replace rebin for non-integer
  0,textregion_ypix,xsize=n_cols/2, ysize=n_rows/2,/device ;removed ,/sample keyword
endif else begin
tv,congrid(byte_image(0:n_cols-1,0:n_rows-1,0),n_cols/2,n_rows/2), $      ; replace rebin for non-integer
  0,textregion_ypix,xsize=n_cols/2, ysize=n_rows/2,/device ;removed ,/sample keyword
endelse
; add scale bar and energy
; ********
; CJJ - replaced to display ONLY name (not path) - APH 16-apr-98
;xyouts,5,fix(0.5*char_ypix),/device,charsize=charsize,font=0, $
;  filename_list(i_file),color=white_color_index
; strip filename
if !VERSION.OS_FAMILY EQ 'unix' then sep = '/' else sep = '\'
file =  string(filename_list(i_file))
file=strmid(file,rstrpos(file,sep)+1,strlen(file))
file = strmid(file,0,strpos(file,'.'))
xyouts,5,fix(0.5*char_ypix),/device,charsize=charsize,font=0, $
  file,color=white_color_index
; APH - end of changes
xyouts,5,fix(2.*char_ypix),/device,charsize=charsize,font=0, $
  strtrim(string(ev(i_file),format='(f10.2)'),2)+' eV',$
  color=white_color_index
;tv,bar,5,fix(3.5*char_ypix),/device
xyouts,(5+bar_pixels+char_ypix),fix(3.5*char_ypix),/device,font=0,$
  charsize=charsize,bar_string,color=white_color_index

return
END


; -------- Routine to display the resulting image
PRO region_analyze_result_disp, image_result
@axis_com
@bsif_com
@stack_process_com
@region_analyze_common
activate_region_test=''
widget_control, region_analyze_par.activate_region, get_value=activate_region_test
wset, region_analyze_par.image_res_win
;takes into account if its a RGB or intensity image
if region_analyze_par.num_reg GE 2 AND activate_region_test EQ 'Region Analyze Activated' THEN BEGIN
	TVSCL, congrid(image_result,n_cols/2,n_rows/2,region_analyze_par.num_reg+1), TRUE=3
endif else begin
	TVSCL, congrid(image_result,n_cols/2,n_rows/2,region_analyze_par.num_reg+1)
endelse

END

;This detect the maxima position (or existance)
PRO region_analyze_maximg, _extra = e
@axis_com
@bsif_com
@stack_process_com
@region_analyze_common
COMMON volume_data, image_stack
;structure for the position of the actual region
reg_pos_struct={reg_pos_struct,$
				pixHorzmin:0L,$
				pixHorzmax:0L,$
				pixVertmin:0L,$
				pixVertmax:0L$
				}

;we want te ba able to cancel
n_reg_horz_str='3';these are the default
n_reg_vert_str='3';these are the default
acceptance_str='20';these are the default
;getting button information
widget_control, region_analyze_par.spect_max.cancel, sensitive=1
widget_control, region_analyze_par.spect_max.region_n_rows, get_value=n_reg_horz_str
widget_control, region_analyze_par.spect_max.region_n_cols, get_value=n_reg_vert_str
widget_control, region_analyze_par.spect_max.acceptance, get_value=acceptance_str
;we build an address matrix of the size of the image
volt_max_incre=0L
address_matrix=LONARR(n_cols,n_rows)
FOR addr_rows=0L, n_rows-1 DO BEGIN
    FOR addr_cols=0L, n_cols-1 DO BEGIN
    address_matrix[addr_cols,addr_rows]=volt_max_incre
    volt_max_incre+=1
    ENDFOR
ENDFOR
;diemnsion of the stack
size_stack_images=UINT(0)
size_stack_images=size(image_stack)
;temporary stack mean of the region for each image
temp_mean_stack_images=LONARR(size_stack_images(3))
;number of region (in vertical and horizontal)
n_reg_horz=UINT(0)
n_reg_vert=UINT(0)
;dimension of region (will be selectable later on)
n_minireg_rows=UINT(n_reg_horz_str(0))
n_minireg_cols=UINT(n_reg_vert_str(0))
;find the number of region
n_reg_vert=UINT(n_cols/n_minireg_cols)
n_reg_horz=UINT(n_rows/n_minireg_rows)
reg_pos_struct.pixHorzmin=UINT(0)
reg_pos_struct.pixHorzmax=UINT(0)
reg_pos_struct.pixVertmin=UINT(0)
reg_pos_struct.pixVertmax=UINT(0)
acceptance_int=UINT(acceptance_str(0))
;detection of the STD TEST
standard_value=''
standard_test2=''
widget_control, region_analyze_par.spect_max.std_value, get_value=standard_value
widget_control, region_analyze_par.spect_max.std_corr_check, get_value=standard_test2
widget_control, region_analyze_par.activate_region, get_value=activate_region_test
;we need to look if there is smaller region needed to fill image
IF (n_rows MOD n_minireg_rows) NE 0 THEN BEGIN
    detec_row=1;marker: we added a region
    n_reg_horz+=1
ENDIF ELSE BEGIN
    detec_row=2;marker: no region added
ENDELSE
if (n_cols MOD n_minireg_cols) NE 0 THEN BEGIN
    detec_col=1;marker: we added a row
    n_reg_vert+=1
ENDIF ELSE BEGIN
    detec_col=2;marker: no row added
ENDELSE
n_minireg_tot=DOUBLE(0)
n_minireg_tot=DOUBLE(n_reg_vert)*DOUBLE(n_reg_horz);total number of region
image_voltage_corresp=FLTARR(n_cols,n_rows)
;matrix containing the region image
IF region_analyze_par.num_reg GT 0 THEN BEGIN
	image_voltage_corresp_region=FLTARR(n_cols,n_rows,region_analyze_par.num_reg+1)
	image_voltage_corresp_region(0:n_cols-1,0:n_rows-1,0:region_analyze_par.num_reg)=0
ENDIF ELSE BEGIN
	image_voltage_corresp_region=FLTARR(n_cols,n_rows,1)
ENDELSE
index_max_spectra_loc=0

n_minireg_incre=0L;number of current region
;structure to store gradiant information
struct_model_myside={value:0.0,sign:0}
struct_gradiant={before_max:struct_model_myside, after_max:struct_model_myside, before_nonmax:struct_model_myside, after_nonmax:struct_model_myside}

region_case_number=0
i_roi=0;we dont want to get an optical density image
i0_roi=0;neither do we want any trace of previous region

;for each region (we are better doing it by row|col increment)
FOR ind_reg_vert=0L, n_reg_vert-1 DO BEGIN
    FOR ind_reg_horz=0L, n_reg_horz-1 DO BEGIN
       ;4 size of possible region(some region may not exist)
       ;--------
       ;|1111|3|;region 1 =good size
       ;|1111|3|;region 2 =lack rows
       ;--------;region 3 =lack cols
       ;|2222|4|;region 4 =lack both
       ;--------
       IF (detec_row EQ 1 && detec_col EQ 1) && n_minireg_incre EQ n_minireg_tot-1 THEN BEGIN
       ;case of region 4
       region_case_number=4
       i0_roi=FLTARR(n_cols-ind_reg_vert*n_minireg_cols,n_rows-ind_reg_horz*n_minireg_rows)
       i0_roi=address_matrix(ind_reg_vert*n_minireg_cols:n_cols-1,ind_reg_horz*n_minireg_rows:n_rows-1)
		reg_pos_struct.pixHorzmin=ind_reg_horz*n_minireg_rows
		reg_pos_struct.pixHorzmax=n_rows-1
		reg_pos_struct.pixVertmin=ind_reg_vert*n_minireg_cols
		reg_pos_struct.pixVertmax=n_cols-1
       ENDIF ELSE BEGIN
         IF detec_row EQ 1 && ind_reg_horz EQ n_reg_horz-1 THEN BEGIN
         ;case of region 2
         region_case_number=2
         i0_roi=FLTARR( n_minireg_cols,n_rows-ind_reg_horz*n_minireg_rows)
         i0_roi=address_matrix(ind_reg_vert*n_minireg_cols:ind_reg_vert*n_minireg_cols+n_minireg_cols-1,ind_reg_horz*n_minireg_rows:n_rows-1)
			reg_pos_struct.pixHorzmin=ind_reg_horz*n_minireg_rows
			reg_pos_struct.pixHorzmax=n_rows-1
			reg_pos_struct.pixVertmin=ind_reg_vert*n_minireg_cols
			reg_pos_struct.pixVertmax=ind_reg_vert*n_minireg_cols+n_minireg_cols-1
         ENDIF ELSE BEGIN
          	IF detec_col EQ 1 && ind_reg_vert EQ n_reg_vert-1 THEN BEGIN
          		;case of region 3
          		region_case_number=3
          		i0_roi=FLTARR(n_cols-ind_reg_vert*n_minireg_cols,n_minireg_rows)
          		i0_roi=address_matrix(ind_reg_vert*n_minireg_cols:n_cols-1,ind_reg_horz*n_minireg_rows:ind_reg_horz*n_minireg_rows+n_minireg_rows-1)
				reg_pos_struct.pixHorzmin=ind_reg_horz*n_minireg_rows
				reg_pos_struct.pixHorzmax=ind_reg_horz*n_minireg_rows+n_minireg_rows-1
				reg_pos_struct.pixVertmin=ind_reg_vert*n_minireg_cols
				reg_pos_struct.pixVertmax=n_cols-1
          	ENDIF ELSE BEGIN
          	;case of region 1
          	region_case_number=1
          	i0_roi=FLTARR(n_minireg_cols,n_minireg_rows)
          	i0_roi=address_matrix(ind_reg_vert*n_minireg_cols:ind_reg_vert*n_minireg_cols+n_minireg_cols-1,ind_reg_horz*n_minireg_rows:ind_reg_horz*n_minireg_rows+n_minireg_rows-1)
			reg_pos_struct.pixHorzmin=ind_reg_horz*n_minireg_rows
			reg_pos_struct.pixHorzmax=ind_reg_horz*n_minireg_rows+n_minireg_rows-1
			reg_pos_struct.pixVertmin=ind_reg_vert*n_minireg_cols
			reg_pos_struct.pixVertmax=ind_reg_vert*n_minireg_cols+n_minireg_cols-1
          	ENDELSE
         ENDELSE

       ENDELSE
       ;
	   n_spect_image=intArr(2)
	   n_spect_image(1)=size_stack_images(3);
		;if there is no region defined or region analyze is de-activated we determine the maxima position
			IF activate_region_test EQ 'Region Analyze De-activated' OR region_analyze_par.num_reg EQ 0 THEN BEGIN
				;if there is no region, we can initialise our matrix (all image)
				if region_analyze_par.num_reg EQ 0 THEN BEGIN
					temp_mean_stack_images=DBLARR(n_spect_image(1))
					EV_matrix_region=DBLARR(n_spect_image(1))
					incre_build_mean_arr=n_spect_image(1)
					FOR incre_mean_arr=0, n_spect_image(1)-1 DO BEGIN
						temp_mean_stack_images(incre_mean_arr)=mean(image_stack(reg_pos_struct.pixVertmin:reg_pos_struct.pixVertmax,reg_pos_struct.pixHorzmin:reg_pos_struct.pixHorzmax,incre_mean_arr))
						EV_matrix_region(incre_mean_arr)=EV(incre_mean_arr)
					ENDFOR
				;if there is 2 region 'wall' we take the image between them
				endif else begin
						min_incre_mean_arr=region_analyze_par.list_reg_img(0)
						max_incre_mean_arr=region_analyze_par.list_reg_img(1)
						temp_mean_stack_images=DBLARR(max_incre_mean_arr-min_incre_mean_arr+1)
						EV_matrix_region=DBLARR(max_incre_mean_arr-min_incre_mean_arr+1)
						incre_build_mean_arr=0
					FOR incre_mean_arr=min_incre_mean_arr, max_incre_mean_arr DO BEGIN
						temp_mean_stack_images(incre_build_mean_arr)=mean(image_stack(reg_pos_struct.pixVertmin:reg_pos_struct.pixVertmax,reg_pos_struct.pixHorzmin:reg_pos_struct.pixHorzmax,incre_mean_arr))
						EV_matrix_region(incre_build_mean_arr)=EV(incre_mean_arr)
						incre_build_mean_arr++
					ENDFOR
				endelse
				;find the max
			    index_max_spectrum=0
				index_max_spectrum=where(temp_mean_stack_images EQ max(temp_mean_stack_images),max_spectrum_count);this give a number from 0 to the number of image
				max_acceptance=0;marker: no max accepted so far
				max_position_marker=0;marker: max not on edge +-1
				;for each max, we look if tis good
				FOR n_max_for=0, max_spectrum_count-1 DO BEGIN

					;is the max the 1rst or 2nd index at beg or end?
					IF (index_max_spectrum(n_max_for) GT 1) && (index_max_spectrum(n_max_for) LT incre_build_mean_arr-2) THEN BEGIN
					;we will now look at the gradiant before and after the max (we want a peak with the gradiant the same
					;between its 2 neighbor
						struct_gradiant.before_max.value=temp_mean_stack_images(index_max_spectrum(n_max_for))-temp_mean_stack_images(index_max_spectrum(n_max_for)-1)
						struct_gradiant.after_max.value=temp_mean_stack_images(index_max_spectrum(n_max_for)+1)-temp_mean_stack_images(index_max_spectrum(n_max_for))
						struct_gradiant.before_nonmax.value=temp_mean_stack_images(index_max_spectrum(n_max_for)-1)-temp_mean_stack_images(index_max_spectrum(n_max_for)-2)
						struct_gradiant.after_nonmax.value=temp_mean_stack_images(index_max_spectrum(n_max_for)+2)-temp_mean_stack_images(index_max_spectrum(n_max_for)+1)
						IF struct_gradiant.before_max.value GT 0 THEN struct_gradiant.before_max.sign=1
						IF struct_gradiant.after_max.value GT 0 THEN struct_gradiant.after_max.sign=1
						IF struct_gradiant.before_nonmax.value GT 0 THEN struct_gradiant.before_nonmax.sign=1
						IF struct_gradiant.after_nonmax.value GT 0 THEN struct_gradiant.after_nonmax.sign=1
						;we must look if the max is good or not
						IF ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)-1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int $
								&& ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)+1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int THEN BEGIN
							;well its 20% near its 2 neighboor, seems to be the spectrum max
							max_acceptance=1;marker: accepted
						ENDIF ELSE BEGIN
							;second criteria, difference is greater than 20%, gradiant test (same sign)
							IF struct_gradiant.before_max.sign EQ struct_gradiant.before_nonmax.sign && struct_gradiant.after_max.sign EQ struct_gradiant.after_nonmax.sign THEN BEGIN
								max_acceptance=1;marker: accepted
							ENDIF
						ENDELSE
					ENDIF ELSE BEGIN
						;at the location the max is..the only test possible is the % of diff w/ is neighboor
						max_position_marker=1;marker:max on edge, trouble ahead lets deal with it
						CASE index_max_spectrum(n_max_for) OF
							0:BEGIN
								IF ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)+1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int THEN BEGIN
									;well its within 20% its only neighboor, we will accept it...
									max_acceptance=1;marker: accepted
								ENDIF
						  	END
							1:BEGIN
								IF ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)-1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int $
										&& ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)+1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int THEN BEGIN
									;well its within 20% its 2 neighboor, we will accept it...
									max_acceptance=1;marker: accepted
								ENDIF
						  	END
							incre_build_mean_arr-2:BEGIN
						    	IF ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)-1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int $
									&& ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)+1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int THEN BEGIN
									;well its within 20% its 2 neighboor, we will accept it...
									max_acceptance=1;marker: accepted
								ENDIF
							END
							incre_build_mean_arr-1:BEGIN
								IF ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)-1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int THEN BEGIN
									;well its within 20% its only neighboor, we will accept it...
									max_acceptance=1;marker: accepted
								ENDIF
							END
					 	ENDCASE
					ENDELSE
					;if max was accepted, put the value of voltage in the image
					IF max_acceptance EQ 1 THEN BEGIN
						CASE region_case_number OF
							1: BEGIN
								image_voltage_corresp(ind_reg_vert*n_minireg_cols:ind_reg_vert*n_minireg_cols+n_minireg_cols-1,ind_reg_horz*n_minireg_rows:ind_reg_horz*n_minireg_rows+n_minireg_rows-1)=EV_matrix_region(index_max_spectrum(n_max_for))
							END
							2: BEGIN
								image_voltage_corresp(ind_reg_vert*n_minireg_cols:ind_reg_vert*n_minireg_cols+n_minireg_cols-1,ind_reg_horz*n_minireg_rows:n_rows-1)=EV_matrix_region(index_max_spectrum(n_max_for))
            	 			END
							3: BEGIN
								image_voltage_corresp(ind_reg_vert*n_minireg_cols:n_cols-1,ind_reg_horz*n_minireg_rows:ind_reg_horz*n_minireg_rows+n_minireg_rows-1)=EV_matrix_region(index_max_spectrum(n_max_for))
							END
							4: BEGIN
								image_voltage_corresp(ind_reg_vert*n_minireg_cols:n_cols-1,ind_reg_horz*n_minireg_rows:n_rows-1)=EV_matrix_region(index_max_spectrum(n_max_for))
							END
						ENDCASE
					BREAK; EXIT FOR
					ENDIF ELSE BEGIN
					;we didnt accept this max, we will put his value at the mean of his neighboor
					temp_mean_stack_images(index_max_spectrum(n_max_for))=(temp_mean_stack_images(index_max_spectrum(n_max_for)+1)+temp_mean_stack_images(index_max_spectrum(n_max_for)-1))/2
					max_acceptance=0
					ENDELSE
				ENDFOR
			ENDIF ELSE BEGIN
			;THIS IS THE CASE OF WHERE SPECTRUM REGION WERE SPECIFIED
			;for each region
			FOR n_spec_reg=0, region_analyze_par.num_reg DO BEGIN
				;determine the image limit of the region
				if n_spec_reg EQ 0 then Begin;for the first region
					min_incre_mean_arr=0
					max_incre_mean_arr=region_analyze_par.list_reg_img(n_spec_reg)
				endif else begin;for the last region
					if n_spec_reg EQ region_analyze_par.num_reg then begin
						min_incre_mean_arr=region_analyze_par.list_reg_img(n_spec_reg-1)
						max_incre_mean_arr=n_spect_image(1)-1
					endif else begin;for every other region
						min_incre_mean_arr=region_analyze_par.list_reg_img(n_spec_reg-1)
						max_incre_mean_arr=region_analyze_par.list_reg_img(n_spec_reg)
					endelse
				endelse
				;we build a binned version (by average) of the stack image of this region
				temp_mean_stack_images2=DBLARR(max_incre_mean_arr-min_incre_mean_arr+1)
				incre_build_mean_arr=0
				FOR incre_mean_arr=min_incre_mean_arr, max_incre_mean_arr DO BEGIN
					temp_mean_stack_images(incre_build_mean_arr)=mean(image_stack(reg_pos_struct.pixVertmin:reg_pos_struct.pixVertmax,$
						reg_pos_struct.pixHorzmin:reg_pos_struct.pixHorzmax,$
						incre_mean_arr))
					temp_mean_stack_images2(incre_build_mean_arr)=mean(image_stack(reg_pos_struct.pixVertmin:reg_pos_struct.pixVertmax,$
						reg_pos_struct.pixHorzmin:reg_pos_struct.pixHorzmax,$
						incre_mean_arr))
						incre_build_mean_arr++
				ENDFOR
				;find max
			    index_max_spectrum=0
				index_max_spectrum=where(temp_mean_stack_images2 EQ max(temp_mean_stack_images2),max_spectrum_count);this give a number from 0 to the number of image
				max_acceptance=0;marker: no max accepted so far
				max_position_marker=0;marker: max not on edge +-1
				;FOR EACH max (not really needed)
				FOR n_max_for=0, max_spectrum_count-1 DO BEGIN
					;we will now look at the gradiant before and after the max
					;we do need to be sur the max isnt the 1rst or 2nd index at beg or end
					IF (index_max_spectrum(n_max_for) GT 1) && (index_max_spectrum(n_max_for) LT incre_build_mean_arr-2) THEN BEGIN
						struct_gradiant.before_max.value=temp_mean_stack_images(index_max_spectrum(n_max_for))-temp_mean_stack_images(index_max_spectrum(n_max_for)-1)
						struct_gradiant.after_max.value=temp_mean_stack_images(index_max_spectrum(n_max_for)+1)-temp_mean_stack_images(index_max_spectrum(n_max_for))
						struct_gradiant.before_nonmax.value=temp_mean_stack_images(index_max_spectrum(n_max_for)-1)-temp_mean_stack_images(index_max_spectrum(n_max_for)-2)
						struct_gradiant.after_nonmax.value=temp_mean_stack_images(index_max_spectrum(n_max_for)+2)-temp_mean_stack_images(index_max_spectrum(n_max_for)+1)
						IF struct_gradiant.before_max.value GT 0 THEN struct_gradiant.before_max.sign=1
						IF struct_gradiant.after_max.value GT 0 THEN struct_gradiant.after_max.sign=1
						IF struct_gradiant.before_nonmax.value GT 0 THEN struct_gradiant.before_nonmax.sign=1
						IF struct_gradiant.after_nonmax.value GT 0 THEN struct_gradiant.after_nonmax.sign=1
						;we must look if the max is good or not
						IF ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)-1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int $
								&& ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)+1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int THEN BEGIN
							;well its 20% near its 2 neighboor, seems to be the spectrum max
							max_acceptance=1;marker: accepted
						ENDIF ELSE BEGIN
							;second criteria, difference is greater than 20%, gradiant test (same sign)
							IF struct_gradiant.before_max.sign EQ struct_gradiant.before_nonmax.sign && struct_gradiant.after_max.sign EQ struct_gradiant.after_nonmax.sign THEN BEGIN
								max_acceptance=1;marker: accepted
							ENDIF
						ENDELSE
					ENDIF ELSE BEGIN
						;at the location the max is..the only test possible is the % of diff w/ is neighboor
						max_position_marker=1;marker:max on edge, trouble ahead lets deal with it
						CASE index_max_spectrum(n_max_for) OF
							0:BEGIN
								IF ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)+1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int THEN BEGIN
									;well its within 20% its only neighboor, we will accept it...
									max_acceptance=1;marker: accepted
								ENDIF
						  	END
							1:BEGIN
								IF ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)-1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int $
										&& ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)+1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int THEN BEGIN
									;well its within 20% its 2 neighboor, we will accept it...
									max_acceptance=1;marker: accepted
								ENDIF
						  	END
							incre_build_mean_arr-2:BEGIN
						    	IF ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)-1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int $
									&& ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)+1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int THEN BEGIN
									;well its within 20% its 2 neighboor, we will accept it...
									max_acceptance=1;marker: accepted
								ENDIF
							END
							incre_build_mean_arr-1:BEGIN
								IF ABS((temp_mean_stack_images(index_max_spectrum(n_max_for)-1)-temp_mean_stack_images(index_max_spectrum(n_max_for)))/temp_mean_stack_images(index_max_spectrum(n_max_for))) LT acceptance_int THEN BEGIN
									;well its within 20% its only neighboor, we will accept it...
									max_acceptance=1;marker: accepted
								ENDIF
							END
					 	ENDCASE
					ENDELSE
					;if max was accepted, put the value of voltage in the image
					IF max_acceptance EQ 1 THEN BEGIN
						;this is a basic test to see if its a noise peak or a real one, we will consider that its noise if the
						;number of standard deviation is not big enought, the user can choose to do or not this test
						standard_test=DOUBLE(0)
						standard_test=DOUBLE(temp_mean_stack_images(index_max_spectrum(n_max_for))-mean(temp_mean_stack_images))/STDDEV(temp_mean_stack_images,/DOUBLE)
						;if the STD test show that it is a peak, or if there is no STD test to be done
						if standard_test GE DOUBLE(standard_value) OR standard_test2 EQ 'STD test is OFF' THEN BEGIN
							;if the max is on the extremum of the spectra its not good, no peak in this region
							if index_max_spectrum(n_max_for) EQ 0 OR index_max_spectrum(n_max_for) EQ region_analyze_par.num_reg-1 then begin
								CASE region_case_number OF
									1: BEGIN
										image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:ind_reg_vert*n_minireg_cols+n_minireg_cols-1,$
											ind_reg_horz*n_minireg_rows:ind_reg_horz*n_minireg_rows+n_minireg_rows-1,n_spec_reg)=0
									END
									2: BEGIN
										image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:ind_reg_vert*n_minireg_cols+n_minireg_cols-1,$
											ind_reg_horz*n_minireg_rows:n_rows-1,n_spec_reg)=0
            	 					END
									3: BEGIN
										image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:n_cols-1,$
											ind_reg_horz*n_minireg_rows:ind_reg_horz*n_minireg_rows+n_minireg_rows-1,n_spec_reg)=0
									END
									4: BEGIN
										image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:n_cols-1,$
											ind_reg_horz*n_minireg_rows:n_rows-1,n_spec_reg)=0
									END
								ENDCASE
								BREAK;EXIT FOR
							;if the peak is elsewhere in the region, its accepted
							endif else begin
								CASE region_case_number OF
									1: BEGIN
										image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:ind_reg_vert*n_minireg_cols+n_minireg_cols-1,$
											ind_reg_horz*n_minireg_rows:ind_reg_horz*n_minireg_rows+n_minireg_rows-1,n_spec_reg)=1
									END
									2: BEGIN
										image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:ind_reg_vert*n_minireg_cols+n_minireg_cols-1,$
											ind_reg_horz*n_minireg_rows:n_rows-1,n_spec_reg)=1
	            		 			END
									3: BEGIN
										image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:n_cols-1,$
											ind_reg_horz*n_minireg_rows:ind_reg_horz*n_minireg_rows+n_minireg_rows-1,n_spec_reg)=1
									END
									4: BEGIN
										image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:n_cols-1,$
											ind_reg_horz*n_minireg_rows:n_rows-1,n_spec_reg)=1
									END
								ENDCASE
								BREAK; EXIT FOR
							endelse
						endif else begin
							;this is noise for the STD test
							CASE region_case_number OF
									1: BEGIN
										image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:ind_reg_vert*n_minireg_cols+n_minireg_cols-1,$
											ind_reg_horz*n_minireg_rows:ind_reg_horz*n_minireg_rows+n_minireg_rows-1,n_spec_reg)=0
									END
									2: BEGIN
										image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:ind_reg_vert*n_minireg_cols+n_minireg_cols-1,$
											ind_reg_horz*n_minireg_rows:n_rows-1,n_spec_reg)=0
            	 					END
									3: BEGIN
										image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:n_cols-1,$
											ind_reg_horz*n_minireg_rows:ind_reg_horz*n_minireg_rows+n_minireg_rows-1,n_spec_reg)=0
									END
									4: BEGIN
										image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:n_cols-1,$
											ind_reg_horz*n_minireg_rows:n_rows-1,n_spec_reg)=0
									END
							ENDCASE
							BREAK;EXIT FOR
						endelse
					;if the max wasnt accepted for its gradiant
					ENDIF ELSE BEGIN
						;if it was on the limit, not a peak
						if index_max_spectrum(n_max_for) EQ 0 OR index_max_spectrum(n_max_for) EQ region_analyze_par.num_reg-1 then begin
							CASE region_case_number OF
								1: BEGIN
									image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:ind_reg_vert*n_minireg_cols+n_minireg_cols-1,$
										ind_reg_horz*n_minireg_rows:ind_reg_horz*n_minireg_rows+n_minireg_rows-1,n_spec_reg)=0
								END
								2: BEGIN
									image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:ind_reg_vert*n_minireg_cols+n_minireg_cols-1,$
										ind_reg_horz*n_minireg_rows:n_rows-1,n_spec_reg)=0
            	 				END
								3: BEGIN
									image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:n_cols-1,$
										ind_reg_horz*n_minireg_rows:ind_reg_horz*n_minireg_rows+n_minireg_rows-1,n_spec_reg)=0
								END
								4: BEGIN
									image_voltage_corresp_region(ind_reg_vert*n_minireg_cols:n_cols-1,$
										ind_reg_horz*n_minireg_rows:n_rows-1,n_spec_reg)=0
								END
							ENDCASE
							BREAK;there is no real peak in there, EXIT FOR
						endif else begin
							;if this is the 3rd max rejected, consider it noise
							if n_max_for GE 3 THEN BREAK
							;we didnt accept this max, we will put his value at the mean of his neighboor
							temp_mean_stack_images(index_max_spectrum(n_max_for))=(temp_mean_stack_images(index_max_spectrum(n_max_for)+1)+temp_mean_stack_images(index_max_spectrum(n_max_for)-1))/2
							max_acceptance=0
						endelse
					ENDELSE
				ENDFOR
			ENDFOR
			ENDELSE
		;count to see where we are and display the %
       n_minireg_incre+=1
       n_max_pourcent=0
		n_max_pourcent=STRING(DOUBLE(DOUBLE(n_minireg_incre*100L)/DOUBLE(n_minireg_tot)))+' % Done'
       widget_control, region_analyze_par.spect_max.generate, set_value=n_max_pourcent
       mysidetest=widget_event(/NOWAIT)
       ;test for cancellation
       widget_control, region_analyze_par.spect_max.cancel,get_value = cancel_test
       IF cancel_test EQ 'Cancelling...' THEN BREAK
    ENDFOR
    IF cancel_test EQ 'Cancelling...' THEN BREAK
ENDFOR
;we only save if not cancelled
IF cancel_test NE 'Cancelling...' THEN BEGIN
region_analyze_save, image_voltage_corresp, image_voltage_corresp_region, n_reg_horz_str,$
					 n_reg_vert_str, acceptance_str, standard_value, std_string, standard_test2
ENDIF ELSE BEGIN
	widget_control, region_analyze_par.spect_max.cancel,set_value = 'Cancel Process'
	widget_control, region_analyze_par.spect_max.generate, set_value='Generate Maxima Image'
ENDELSE
END

;list of event
PRO region_analyze_event, event, _extra = e
@axis_com
@bsif_com
@stack_process_com
@region_analyze_common

COMMON volume_data, image_stack
COMMON pix_shift, xpix_shift, ypix_shift
on_error, 2

CASE event.id OF
	region_analyze_par.spectrum_disp: BEGIN
	 	if Event.Type EQ 1 AND Event.Release EQ 1b then begin;if user click
		    ; APH 1-jul-98 : cursor selection of display image
		    wset,region_analyze_par.plot_win
			if spectrum_x_scale(0) NE spectrum_x_scale(1) then begin; kluge (aph 30-may-03)
			    !X.s=spectrum_x_scale
			    !Y.s=spectrum_y_scale
			    curval = CONVERT_COORD(Event.X, Event.Y, /DEVICE, /TO_DATA)
			endif
		    new_E = curval(0)
		    i_file = displayed_file_index
		    i_file_old = i_file
		    ind = where(eV GE new_E,count)
		    if count GT 0 then begin
		    	i_file = ind(0)
		    endif else begin
				i_file=0
			endelse
			count2=0
			if i_file NE 0 then	test_num_reg=where(region_analyze_par.list_reg_img EQ i_file, count2)
			if ((region_analyze_par.num_reg LT 20) AND (i_file NE 0)) AND (count2 EQ 0)  then begin
				region_analyze_par.list_reg(region_analyze_par.num_reg)=eV(i_file)
				region_analyze_par.list_reg_img(region_analyze_par.num_reg)=i_file
				region_analyze_par.list_reg_Xpos(region_analyze_par.num_reg)=eV(i_file)
				region_analyze_par.num_reg++
				widget_control, region_analyze_par.list_region_lbl, set_value=region_analyze_par.list_reg
			endif
		    displayed_file_index = i_file
;		    stack_analyze_makespectrum				; removed as crashes plot on read in

		    ;region_analyze_plotspectrum,displayed_file_index, region_analyze_par.num_reg
			region_analyze_plotspectrum, region_analyze_par.list_reg_img
	    endif
	END
	;no real event related to the table
	region_analyze_par.list_region_lbl:BEGIN

	END
	;start defining region(or stop)
	region_analyze_par.add_reg:BEGIN
		widget_control, region_analyze_par.add_reg,$
			get_value= test_add_reg

		if test_add_reg EQ "Define region" then begin
			widget_control, region_analyze_par.add_reg,$
				set_value = "Stop defining region"
			region_analyze_desensitive

		endif else begin
			widget_control, region_analyze_par.add_reg,$
				set_value = "Define region"
			region_analyze_sensitive
			reorgan_arr=region_analyze_par.list_reg(0:region_analyze_par.num_reg-1)
			reorgan_arr2=region_analyze_par.list_reg_img(0:region_analyze_par.num_reg-1)
			reorgan_arr3=region_analyze_par.list_reg_Xpos(0:region_analyze_par.num_reg-1)

			region_analyze_par.list_reg=reorgan_arr(SORT(reorgan_arr2))
			region_analyze_par.list_reg_img=reorgan_arr2(SORT(reorgan_arr2))
			region_analyze_par.list_reg_Xpos=reorgan_arr3(SORT(reorgan_arr2))
			widget_control, region_analyze_par.list_region_lbl, set_value=region_analyze_par.list_reg
		endelse

	END

	;remove region button
	region_analyze_par.remove_reg:begin
	region_analyze_remove_reg
	region_analyze_plotspectrum, region_analyze_par.list_reg_img


	END
	;reset region button
	region_analyze_par.reset_reg:begin
	region_analyze_reset_reg


	END
	;close window button
	region_analyze_par.close_windows:begin
		widget_control, region_analyze_par.main_base, /DESTROY

	end

	region_analyze_par.image_label:begin
			if event.type EQ 1 then begin
                x_index = floor(0.5 +float(event.x)*2)
                y_index = floor(0.5 +float(event.y-textregion_ypix)*2)
				;  adapt for image zoom conditions
 				ixslope = (ixh - ixl)/(n_cols-1)
				iyslope = (iyh - iyl)/(n_rows-1)
                x_index = fix(x_index*ixslope + ixl)
                y_index = fix(y_index*iyslope + iyl)
                roi = [x_index+y_index*n_cols]

                    i0_roi = roi

                stack_analyze_makespectrum
                region_analyze_plotspectrum,region_analyze_par.list_reg_img
                region_analyze_imgdisp,region_analyze_par.list_reg_img

            ENDif
	end
;generate the map
	region_analyze_par.spect_max.generate:BEGIN
		region_analyze_desensitive
		widget_control, region_analyze_par.add_reg, sensitive=0
		activate_region_test=''
		widget_control, region_analyze_par.activate_region, get_value=activate_region_test
		;which test?
		if activate_region_test EQ 'Region Analyze De-activated' THEN BEGIN
			;we need either 0 or 2 region wall for this test, otherwise its not correct
			if region_analyze_par.num_reg EQ 0 OR region_analyze_par.num_reg EQ 2 THEN BEGIN
				region_analyze_maximg
			endif else begin
				;stop all action in the region analyze windows
				region_analyze_mass_desensitive
				;create a warning widget
				region_analyze_warning={region_analyze_warning,$
						main_base:0L,$
						mes:0L,$
						mes_button:0L $
						}
		 		region_analyze_warning.main_base=widget_base(title="Warning!",/column)
		 		row1=widget_base(region_analyze_warning.main_base,/row)
		 		col1=widget_base(row1,/column)
		 		region_analyze_warning.mes=widget_label(row1,value="You must choose either 0 or 2 separation first. Thx.")
				row=widget_base(row1,/row)
		 		region_analyze_warning.mes_button=widget_button(row,value="Ok")
		 		widget_control, region_analyze_warning.main_base, /realize
		 		region_analyze_warn_test=widget_event(region_analyze_warning.mes_button)
				widget_control, region_analyze_warning.main_base, /DESTROY
			endelse
		endif else begin
				;start the analyze
				region_analyze_maximg
		endelse

		;looking if it was cancelled
		cancel_test='0'
		widget_control, region_analyze_par.spect_max.cancel,get_value = cancel_test
		widget_control, region_analyze_par.add_reg, sensitive=1
		region_analyze_sensitive
		IF cancel_test EQ 'Cancelling...' THEN BEGIN
		widget_control, region_analyze_par.spect_max.cancel,set_value='Cancel Process'
		cancel_test='0'


		ENDIF

	END
	;cancel button
	region_analyze_par.spect_max.cancel:BEGIN

		widget_control, region_analyze_par.spect_max.cancel,set_value = 'Cancelling...'

	END

	;activate region analyze button
	region_analyze_par.activate_region:BEGIN
		test_activate_region=''
		widget_control, region_analyze_par.activate_region,get_value=test_activate_region
		CASE test_activate_region OF
				'Region Analyze De-activated':BEGIN
					widget_control, region_analyze_par.activate_region,set_value='Region Analyze Activated'
				END

				'Region Analyze Activated':BEGIN
					widget_control, region_analyze_par.activate_region,set_value='Region Analyze De-activated'
				END

		ENDCASE
	END
	;number of column for the region
	region_analyze_par.spect_max.region_n_cols:BEGIN
		region_n_cols=3L;default value
        temp_string = ''
        widget_control, region_analyze_par.spect_max.region_n_cols,$
          get_value = temp_string
        on_ioerror, region_n_cols_oops
        reads,temp_string(0),region_n_cols
        region_n_cols_oops:
        widget_control, region_analyze_par.spect_max.region_n_cols, $
          set_value = strtrim(string(region_n_cols,format='(f10.2)'),2)


	END
	;number of row for the region
	region_analyze_par.spect_max.region_n_rows:BEGIN

		region_n_rows=3L;default value
        temp_string = ''
        widget_control, region_analyze_par.spect_max.region_n_rows,$
          get_value = temp_string
        on_ioerror, region_n_rows_oops
        reads,temp_string(0),region_n_rows
        region_n_rows_oops:
        widget_control, region_analyze_par.spect_max.region_n_rows, $
          set_value = strtrim(string(region_n_rows,format='(f10.2)'),2)

	END
	;acceptance
	region_analyze_par.spect_max.acceptance:BEGIN
		acceptance=20L;default value
        temp_string = ''
        widget_control, region_analyze_par.spect_max.acceptance,$
          get_value = temp_string
        on_ioerror, acceptance_oops
        reads,temp_string(0),acceptance
        acceptance_oops:
        widget_control, region_analyze_par.spect_max.acceptance, $
          set_value = strtrim(string(acceptance,format='(f10.2)'),2)
	END

	;standard deviation button
	region_analyze_par.spect_max.std_corr_check:BEGIN
		widget_control, region_analyze_par.spect_max.std_corr_check, get_value=std_corr_check_test
	 	CASE std_corr_check_test OF

		'STD test is OFF':BEGIN
			widget_control, region_analyze_par.spect_max.std_corr_check, set_value='STD test is ON'
			END
		'STD test is ON':BEGIN
			widget_control, region_analyze_par.spect_max.std_corr_check, set_value='STD test is OFF'
			END
		ENDCASE

	END
	;saving binning
	region_analyze_par.sav_bin:BEGIN
		region_analyze_sav_bin_test
	END

ENDCASE


END
;this look if the division of the image by the save binning give an integer
PRO region_analyze_sav_bin_test
@region_analyze_common
@axis_com
@bsif_com
@stack_process_com
sav_bin_test_str=''
widget_control, region_analyze_par.sav_bin, get_value=sav_bin_test_str
sav_bin_test_int=0
sav_bin_test_int=UINT(sav_bin_test_str)
if (sav_bin_test_int GT 0 and (n_cols MOD sav_bin_test_int EQ 0)) AND (n_rows MOD sav_bin_test_int EQ 0) then begin
endif else begin
widget_control, region_analyze_par.sav_bin, set_value='1'
endelse

END
;useless
PRO region_analyze_def_reg
	@region_analyze_common

END
;remove the region selected
PRO region_analyze_remove_reg
@region_analyze_common
@axis_com
@bsif_com
@stack_process_com
test_select_region=widget_info(region_analyze_par.list_region_lbl,/LIST_SELECT)
IF test_select_region EQ -1 OR test_select_region $
	GE region_analyze_par.num_reg THEN BEGIN;no region selected, what do we kill?

ENDIF ELSE BEGIN;region selected, kill it.
	;we simply remake the list without the deleted element
	rebuild_incre=0
	list_reg_temp=region_analyze_par.list_reg
	list_reg_img_temp=region_analyze_par.list_reg_img
	list_reg_Xpos_temp=region_analyze_par.list_reg_Xpos
	for I=0, region_analyze_par.num_reg-1 DO BEGIN
		if test_select_region EQ I then begin


		endif else begin
		region_analyze_par.list_reg(rebuild_incre)=list_reg_temp(I)
		region_analyze_par.list_reg_img(rebuild_incre)=list_reg_img_temp(I)
		region_analyze_par.list_reg_Xpos(rebuild_incre)=list_reg_Xpos_temp(I)
		rebuild_incre++
		endelse
	ENDFOR
	region_analyze_par.list_reg(region_analyze_par.num_reg-1)=""
	region_analyze_par.list_reg_img(region_analyze_par.num_reg-1)=""
	region_analyze_par.list_reg_Xpos(region_analyze_par.num_reg-1)=""
	region_analyze_par.num_reg--
	widget_control, region_analyze_par.list_region_lbl, set_value=region_analyze_par.list_reg
ENDELSE


END


; --------- remove all region

PRO region_analyze_reset_reg
@region_analyze_common
for I=0, region_analyze_par.num_reg-1 DO BEGIN
	region_analyze_par.list_reg(I)=""
	region_analyze_par.list_reg_img(I)=""
	region_analyze_par.list_reg_Xpos(I)=""
ENDFOR
region_analyze_par.num_reg=0
widget_control, region_analyze_par.list_region_lbl, set_value=region_analyze_par.list_reg

END

;save the result
PRO region_analyze_save, image_voltage_corresp, image_voltage_corresp_region, n_reg_horz_str, n_reg_vert_str, acceptance_str, standard_value, std_string, standard_test2
@region_analyze_common
@axis_com
@bsif_com
@stack_process_com


activate_region_test=''
binning_value=UINT(0)
widget_control, region_analyze_par.activate_region, get_value=activate_region_test
widget_control, region_analyze_par.spect_max.generate, set_value='Saving files...'
widget_control, region_analyze_par.sav_bin, get_value=binning_value_str
binning_value=UINT(binning_value_str)
;different save depending on the test done
IF region_analyze_par.num_reg EQ 0 OR activate_region_test EQ 'Region Analyze De-activated' THEN BEGIN
	image_dimension=size(image_voltage_corresp)
	image_voltage_binned=DBLARR(image_dimension(1)/binning_value(0),image_dimension(2)/binning_value(0))
	image_voltage_binned=REBIN(image_voltage_corresp,image_dimension(1)/binning_value,image_dimension(2)/binning_value)
	;saving .sav IDL file
	file_name_build=""
	file_name_build=DEFPATH+"MaximaImage_"+n_reg_horz_str+"_"+n_reg_vert_str+"_"+acceptance_str+"_"+STRCOMPRESS(STRING(min(image_voltage_corresp)),/REMOVE_ALL)+"_"+STRCOMPRESS(STRING(max(image_voltage_corresp)),/REMOVE_ALL)+".sav"
	SAVE, image_voltage_corresp , FILENAME = file_name_build
	file_name_build=""
	file_name_build=DEFPATH+"MaximaImage_"+n_reg_horz_str+"_"+n_reg_vert_str+"_"+acceptance_str+"_"+STRCOMPRESS(STRING(min(image_voltage_corresp)),/REMOVE_ALL)+"_"+STRCOMPRESS(STRING(max(image_voltage_corresp)),/REMOVE_ALL)+".csv"
	OPENW, 1, file_name_build
	FOR addr_rows=0L, (image_dimension(2)/binning_value(0))-1 DO BEGIN
    	FOR addr_cols=0L, (image_dimension(1)/binning_value(0))-1 DO BEGIN
			PRINTF, 1, STRING(addr_cols)+','+STRING(addr_rows)+','+STRING(image_voltage_binned(addr_cols,addr_rows))
    	ENDFOR
	ENDFOR

	CLOSE, 1

	;saving .gif image
	file_name_build=""
	file_name_build=DEFPATH+"MaximaImage_"+n_reg_horz_str+"_"+n_reg_vert_str+"_"+acceptance_str+"_"+STRCOMPRESS(STRING(min(image_voltage_corresp)),/REMOVE_ALL)+"_"+STRCOMPRESS(STRING(max(image_voltage_corresp)),/REMOVE_ALL)+".gif"
	region_analyze_result_disp, image_voltage_corresp
	WRITE_GIF, file_name_build, TVRD()

ENDIF ELSE BEGIN
	std_string=''
	image_dimension=size(image_voltage_corresp_region)
	image_voltage_binned=DBLARR(image_dimension(1)/binning_value(0),image_dimension(2)/binning_value(0),image_dimension(3))
	image_voltage_binned=REBIN(image_voltage_corresp_region,image_dimension(1)/binning_value(0),image_dimension(2)/binning_value(0),image_dimension(3))
	if standard_test2 EQ 'STD test is OFF' THEN BEGIN
		std_string='StdOff'
	endif else begin
		std_string='StdOn'+standard_value
	endelse
	file_name_build=""
	file_name_build=DEFPATH+"CompositeImage_"+n_reg_horz_str+"_"+n_reg_vert_str+"_"+acceptance_str+std_string+".sav"
	SAVE, image_voltage_corresp_region , FILENAME = file_name_build

	for save_reg=0, region_analyze_par.num_reg do begin
		file_name_build=""
		file_name_build=DEFPATH+"Composite_"+n_reg_horz_str+"_"+n_reg_vert_str+"_"+acceptance_str+"_"+STRCOMPRESS(STRING(save_reg),/REMOVE_ALL)+"of"+STRCOMPRESS(STRING(region_analyze_par.num_reg),/REMOVE_ALL)+std_string+".csv"
		OPENW, 1, file_name_build
		FOR addr_rows=0L, (image_dimension(2)/binning_value(0))-1 DO BEGIN
    		FOR addr_cols=0L, (image_dimension(1)/binning_value(0))-1 DO BEGIN
				PRINTF, 1, STRING(addr_cols)+','+STRING(addr_rows)+','+STRING(image_voltage_binned(addr_cols,addr_rows,save_reg))
    		ENDFOR
		ENDFOR
		CLOSE, 1
	endfor
	file_name_build=DEFPATH+"CompositeImage_"+n_reg_horz_str+"_"+n_reg_vert_str+"_"+acceptance_str+std_string+".gif"
	region_analyze_result_disp, image_voltage_corresp_region

	WRITE_GIF, file_name_build, TVRD()
ENDELSE
widget_control, region_analyze_par.spect_max.generate, set_value='Generate Maxima Image'


END

;disable some button
PRO region_analyze_desensitive
@region_analyze_common
	widget_control, region_analyze_par.spectrum_disp, sensitive = 1
	widget_control, region_analyze_par.add_reg, sensitive = 1
	widget_control, region_analyze_par.remove_reg, sensitive = 0
	widget_control, region_analyze_par.reset_reg, sensitive = 0
	widget_control, region_analyze_par.close_windows, sensitive = 0
	widget_control, region_analyze_par.list_region_lbl, sensitive= 0
	widget_control, region_analyze_par.spect_max.generate, sensitive=0
	widget_control, region_analyze_par.spect_max.region_n_cols, sensitive=0
	widget_control, region_analyze_par.spect_max.region_n_rows,sensitive=0
	widget_control, region_analyze_par.spect_max.acceptance, sensitive=0
	widget_control, region_analyze_par.sav_bin, sensitive=0
	widget_control, region_analyze_par.activate_region,sensitive=0
	widget_control, region_analyze_par.spect_max.std_corr_check, sensitive=0
	widget_control, region_analyze_par.spect_max.std_lbl, sensitive=0
	widget_control, region_analyze_par.spect_max.std_value, sensitive=0
END
;disable all button
PRO region_analyze_mass_desensitive
	@region_analyze_common
	widget_control, region_analyze_par.spectrum_disp, sensitive = 0
	widget_control, region_analyze_par.add_reg, sensitive = 0
	widget_control, region_analyze_par.remove_reg, sensitive = 0
	widget_control, region_analyze_par.reset_reg, sensitive = 0
	widget_control, region_analyze_par.close_windows, sensitive = 0
	widget_control, region_analyze_par.list_region_lbl, sensitive= 0
	widget_control, region_analyze_par.spect_max.generate, sensitive=0
	widget_control, region_analyze_par.spect_max.region_n_cols, sensitive=0
	widget_control, region_analyze_par.spect_max.region_n_rows,sensitive=0
	widget_control, region_analyze_par.spect_max.acceptance, sensitive=0
	widget_control, region_analyze_par.spect_max.cancel, sensitive=0
	widget_control, region_analyze_par.sav_bin, sensitive=0
	widget_control, region_analyze_par.activate_region,sensitive=0
	widget_control, region_analyze_par.spect_max.std_corr_check, sensitive=0
	widget_control, region_analyze_par.spect_max.std_lbl, sensitive=0
	widget_control, region_analyze_par.spect_max.std_value, sensitive=0
END
;enable all button needed
PRO region_analyze_mass_sensitive
	@region_analyze_common
	widget_control, region_analyze_par.spectrum_disp, sensitive = 0
	widget_control, region_analyze_par.add_reg, sensitive = 1
	widget_control, region_analyze_par.remove_reg, sensitive = 1
	widget_control, region_analyze_par.reset_reg, sensitive = 1
	widget_control, region_analyze_par.close_windows, sensitive = 1
	widget_control, region_analyze_par.list_region_lbl, sensitive= 1
	widget_control, region_analyze_par.spect_max.generate, sensitive=1
	widget_control, region_analyze_par.spect_max.region_n_cols, sensitive=1
	widget_control, region_analyze_par.spect_max.region_n_rows,sensitive=1
	widget_control, region_analyze_par.spect_max.acceptance, sensitive=1
	widget_control, region_analyze_par.spect_max.cancel, sensitive=0
	widget_control, region_analyze_par.sav_bin, sensitive=1
	widget_control, region_analyze_par.activate_region,sensitive=1
	widget_control, region_analyze_par.spect_max.std_corr_check, sensitive=1
	widget_control, region_analyze_par.spect_max.std_lbl, sensitive=1
	widget_control, region_analyze_par.spect_max.std_value, sensitive=1
end

;enable some button
PRO region_analyze_sensitive
@region_analyze_common
	widget_control, region_analyze_par.spectrum_disp, sensitive = 0
	widget_control, region_analyze_par.add_reg, sensitive = 1
	widget_control, region_analyze_par.remove_reg, sensitive = 1
	widget_control, region_analyze_par.reset_reg, sensitive = 1
	widget_control, region_analyze_par.close_windows, sensitive = 1
	widget_control, region_analyze_par.list_region_lbl, sensitive= 1
	widget_control, region_analyze_par.spect_max.generate, sensitive=1
	widget_control, region_analyze_par.spect_max.region_n_cols, sensitive=1
	widget_control, region_analyze_par.spect_max.region_n_rows,sensitive=1
	widget_control, region_analyze_par.spect_max.acceptance, sensitive=1
	widget_control, region_analyze_par.spect_max.cancel, sensitive=0
	widget_control, region_analyze_par.sav_bin, sensitive=1
	widget_control, region_analyze_par.activate_region,sensitive=1
	widget_control, region_analyze_par.spect_max.std_corr_check, sensitive=1
	widget_control, region_analyze_par.spect_max.std_lbl, sensitive=1
	widget_control, region_analyze_par.spect_max.std_value, sensitive=1
END

;plot the spectrum of the selected pixel
PRO region_analyze_plotspectrum, i_file, _extra = e
@axis_com
@bsif_com
@stack_process_com
@region_analyze_common
COMMON volume_data, image_stack

wset,region_analyze_par.plot_win
erase

svec = size(spectrum)
IF (svec(0) EQ 0) THEN return
!y.range=0       ; force auto rescaling
!x.range=0
; set limits to user-specified energy range
plot,ev,spectrum,xtitle='eV',ytitle=spectrum_title,xrange=[disp_emin,disp_emax], $
     yrange=[disp_zmin,disp_zmax], color=white_color_index, psym = 0, ynozero = 1

IF (n_params() NE 0) THEN BEGIN
	FOR i=0, region_analyze_par.num_reg-1 DO BEGIN
    plots,ev(i_file(i))+[0.,0.],!y.crange,color=white_color_index
	;    plots,ev(i_file)+[0.,0.],!y.crange,color=i_color_index
	ENDFOR
ENDIF

spectrum_x_scale = !x.s
spectrum_y_scale = !y.s

return
END

;------------- this is the main widget, which is called from rstack_analyze

PRO Region_analyze

@region_analyze_common
@axis_com
@bsif_com
@stack_process_com

COMMON volume_data, image_stack
COMMON pix_shift, xpix_shift, ypix_shift

;temporary for testing

;some dimension information
plot_cols=640
plot_rows=480
comp_screen_res=GET_SCREEN_SIZE()
;structure to avoid having one really big structure or a massive common file
spect_max_design= $
    		  { spect_max, $
    		  generate:0L, $
    			cancel:0L, $
    			region_n_cols:0L, $
    			region_n_rows:0L, $
    			acceptance:0L, $
    			std_corr_check:0L,$
				std_lbl:0L,$
				std_value:DOUBLE(0), $
    			region_edit:0L $
    			}

  region_analyze_par=$
	{ region_analyze_par, $
	main_base:0L,$
	spectrum_disp:0L,$
	add_reg:0L,$
	remove_reg:0L,$
	reset_reg:0L,$
	list_region_lbl:0L,$
	close_windows:0L, $
	plot_win:0L, $
	num_reg:0L, $
	list_reg:STRARR(20), $
	list_reg_img:DBLARR(20), $
	list_reg_Xpos:DBLARR(20), $
	composite_image:0L, $
	image_label:0L, $
	image_win:0L,$
	sav_bin:0L,$
	sav_bin_lbl:0L,$
	image_result:0L,$
	image_res_win:0L,$
	activate_region:0L,$
	spect_max:spect_max_design $
	}


;main widget, dimension based on the screen resolution, scrollbar added to ensure user can see evrything
comp_screen_res=GET_SCREEN_SIZE()

IF !version.os_family EQ 'Windows' then begin
	region_analyze_par.main_base=widget_base(title='Region Selection', /column, /scroll)
ENDIF else begin
	region_analyze_par.main_base=widget_base(title='Region Selection', /column, /scroll, $
	          X_SCROLL_SIZE=comp_screen_res(0)*.75,Y_SCROLL_SIZE=comp_screen_res(1)*.95)
ENDELSE


row1=widget_base(region_analyze_par.main_base,/row)
row2=widget_base(region_analyze_par.main_base,/row)
col1=widget_base(row1,/column)
col2=widget_base(row1,/column)
col3=widget_base(row1,/column)
col6=widget_base(row1,/column)
col4=widget_base(row2,/column)
col5=widget_base(row2,/column)

base = widget_base(col1, /column, /frame)
row=widget_base(base,/row)
tlabel=widget_label(row, value= 'Spectrum Max Analysis Image Generation')
row=widget_base(base,/row)
region_analyze_par.spect_max.generate= $
	widget_button(row,value='Generate Maxima Image')
region_analyze_par.spect_max.cancel= $
	widget_button(row,value='Cancel Process')
region_analyze_par.activate_region=$
	widget_button(row,value='Region Analyze De-activated')
row=widget_base(base,/row)
tlabel=widget_label(row, value='Regions Size: rows, cols:')
region_analyze_par.spect_max.region_n_cols = $
  widget_text(row,/frame,/editable,xsize=10)
region_analyze_par.spect_max.region_n_rows = $
  widget_text(row,/frame,/editable,xsize=10)
tlabel=widget_label(row, value='pixels')
row=widget_base(base,/row)
tlabel=widget_label(row, value='Maximum % acceptance')
region_analyze_par.spect_max.acceptance= $
	widget_text(row,/frame, /editable,xsize=3)
;row=widget_base(base,/row)

;region_analyze_par.spect_max.region_edit=$
	;widget_button(row,value='Select Region')
region_analyze_par.spect_max.std_corr_check=$
	widget_button(row,value='STD test is OFF')
region_analyze_par.spect_max.std_lbl=$
	widget_label(row,value='# STD:')
region_analyze_par.spect_max.std_value=$
	widget_text(row,/frame,/editable,xsize=4)
base=widget_base(col2,/column,/frame)
region_analyze_par.sav_bin_lbl=$
	widget_label(base,value='Saving binning:')
row=widget_base(base,/row)
region_analyze_par.sav_bin=$
	widget_text(row,/frame,/editable,xsize=4)

base=widget_base(col3,/column,/frame)

region_analyze_par.list_region_lbl=$
	widget_list(base,value=region_analyze_par.list_reg,xsize=40, ysize=10)



base=widget_base(col6,/column,/frame)

row=widget_base(base,/row)

region_analyze_par.add_reg=$
	widget_button(row,value="Define region")

row=widget_base(base,/row)

region_analyze_par.remove_reg=$
	widget_button(row,value='Remove Region')

row=widget_base(base,/row)

region_analyze_par.reset_reg=$
	widget_button(row, value='Clear Region')

row=widget_base(base,/row)

region_analyze_par.close_windows=$
	widget_button(row,value='Close Region Windows')


row=widget_base(col4,/row)

;spectrum show
region_analyze_par.spectrum_disp=$
	widget_draw(row,$
	MOTION_EVENTS=0, BUTTON_EVENTS=1,$
	xsize=plot_cols, ysize=plot_rows,retain=2)


base=widget_base(col5,/row)

region_analyze_par.image_label=$
	widget_draw(base,xsize=n_cols/2,ysize=n_rows/2+textregion_ypix,retain=2,/button_events)

row=widget_base(base, /row)

region_analyze_par.image_result=$
	widget_draw(base,xsize=n_cols/2,ysize=n_rows/2,retain=2)


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

widget_control, region_analyze_par.main_base, /realize
;we set the start sensitivity
widget_control, region_analyze_par.spectrum_disp, sensitive=0
widget_control, region_analyze_par.add_reg, sensitive=1
widget_control, region_analyze_par.remove_reg,sensitive=1
widget_control, region_analyze_par.reset_reg,sensitive=1
widget_control, region_analyze_par.list_region_lbl, sensitive=1
widget_control, region_analyze_par.close_windows, sensitive=1

widget_control, region_analyze_par.image_label, sensitive=1
widget_control, region_analyze_par.spect_max.generate, sensitive=1
widget_control, region_analyze_par.activate_region,sensitive=1
widget_control,	region_analyze_par.spect_max.cancel, sensitive=0
widget_control, region_analyze_par.spect_max.region_n_cols, sensitive=1
widget_control, region_analyze_par.spect_max.region_n_rows, sensitive=1
widget_control, region_analyze_par.spect_max.acceptance, sensitive=1

widget_control, region_analyze_par.spect_max.region_n_cols, set_value='3'
widget_control, region_analyze_par.spect_max.region_n_rows, set_value='3'
widget_control, region_analyze_par.spect_max.acceptance, set_value='20'
widget_control, region_analyze_par.spect_max.std_corr_check, set_value='STD test is OFF'
widget_control, region_analyze_par.spect_max.std_value, set_value='2.00'

widget_control, region_analyze_par.sav_bin, sensitive=1
widget_control, region_analyze_par.sav_bin, set_value='1'

widget_control,region_analyze_par.image_label,get_value=window
region_analyze_par.image_win=window
wset,window
tvlct,r,g,b

widget_control,region_analyze_par.spectrum_disp,get_value=window
region_analyze_par.plot_win = window
wset,window
tvlct,r,g,b

widget_control,region_analyze_par.image_result,get_value=window
region_analyze_par.image_res_win=window
wset,window
tvlct,r,r,r

xmanager, 'region_analyze', region_analyze_par.main_base, $
  group_leader = region_analyze_par.main_base
region_analyze_imgdisp,displayed_file_index
region_analyze_plotspectrum,displayed_file_index
;event_name=Widget_event()
;region_analyze_event, event_name
END

