; Copyright (c) 1998-2019 A.P. Hitchcock  All rights reserved
;+
;NAME: SOLEIL_PYTCHO_BACKGROUND
;
;
;LAST CHANGED: ----------------------------------- 	23 May 2019

; PURPOSE:
;	This function averages all the background images from ptycho measurements made at Soleil
;
; CATEGORY:
;	    Runs stand alone or inside aXis2000.
;
; CALLING SEQUENCE:
; for procedures:
;	PRO_NAME = PRO_NAME, parameters
;
; for functions
;   RESULT = soleil_ptycho_bgnd(axis_on = axis_on)
;
; INPUTS:
;
; KEYWORDS:
;	AXIS_ON:  if set, called from aXis2000
;
; OUTPUTS:
;	*.(dat,ncb) written
;
; COMMON BLOCKS:
; AXIS_COM    standard set of common blocks
; PTYCHO_COM  ptycho common block

; MODIFICATION HISTORY:
; (23-May-19 aph) first version
;-

FUNCTION soleil_ptycho_bgnd, axis_on = axis_on
@axis_com
@ptycho_com
on_error,2

; ----------- generate background from average of images recorded with shutter closed

		bgnd_names = dialog_pickfile(title = 'Please select all background images', $
	              filter='*.tif', /multiple_files, path=  DefPath, get_path=DefPath)
	    if bgnd_names(0) EQ '' then return, 0
	    t = ax_name(bgnd_names(0))
	    fileshort = strmid(t(1),0, 7)
		WIDGET_CONTROL, /hourglass
	    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))

; ---- save the background image
		t = size(ptycho_bgnd)
		x = findgen(t(1))
		y = findgen(t(2))

		if n_elements(ptycho_e) EQ 0 then begin
			if keyword_Set(axis_on) 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)
		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)
		return, tmp
	END

