; Copyright (c) 1998-2018 A.P. Hitchcock  All rights reserved
;+
;NAME:
;		H5_READ_SGM_IMAGE
;
;LAST CHANGED: ----------------------------------- 	25-Nov-2018 (aph)
;
; PURPOSE:
;	This function reads images from hdf5 files written from the SGM acquisition system
; (version April 2018, JJ Dynes) using the IDL H5_browser for input  (which is a KLUGE)
; and returns an aXis format *.axb IDL structure
;
; CATEGORY:
;	data read-in; operates stand alone or in aXi2000
;
; CALLING SEQUENCE:
;	Result = H5_READ_SGM_IMAGE(file=file, silent = silent)
;
; INPUTS: keyword only
;
; KEYWORDS:
;	FILE	name of file
;	SILENT 	suppress all tag lines
;	STRUCT	return all content of (entry1\data)  as IDL structure
;	TEY		total electron yield channel
;	DIODE	transmission (diode) channel
;	DWELL	dwell time map
;	IO		Io channel
;	NORM	normalize to Io
;	PFYA	average partial fluorescence yield spectrum (to define channels)
;	PFYR	read partial fluorescence yield signals in defined peaks (4 channel stack)
;   SDD		SDD spectra of channels (huge!)
;
; OUTPUTS:
;	Returns an aXis format image (for the extracted STXM file)
;
; COMMON BLOCKS:
;	AXIS_COM	standard set of common blocks
;	bsif_com
;	stack_process_com
;   volume_data, image_stack
;
; DETAILS OF SGM_IMAGE HDF5 data file  (NB 120x120 image with 7 channels of data is 120 Mb !!
;   _NAME           STRING    'data'
;   _ICONTYPE       STRING    ''
;   _TYPE           STRING    'GROUP'
;   _FILE           STRING    'Z:\aXis-Pass-Test-data\SGM-stacks\SGM_1image.hdf5'
;   _PATH           STRING    '/entry1'
;   _COMMENT        STRING    ''
;   CLOCK_PROCESSED STRUCT    -> <Anonymous> Array[1]		dwell at each pixel (nx,ny)
;   DIODE_PROCESSED STRUCT    -> <Anonymous> Array[1]		transmission (Si diode) data (nx,ny)
;   EN_PROCESSED    STRUCT    -> <Anonymous> Array[1]		photon energy  (1D array if a stack)
;   HEX_XP_PROCESSED STRUCT    -> <Anonymous> Array[1]		x - positions (nx)
;   HEX_YP_PROCESSED STRUCT    -> <Anonymous> Array[1]		y - positions (ny)
;   IO_PROCESSED    STRUCT    -> <Anonymous> Array[1]		io data (upstream Au mesh TEY) (nx,ny)
;   SDD_PROCESSED   STRUCT    -> <Anonymous> Array[1]		full SDD spectra (4, 256, nx, ny)	HUGE !
;   TEY_PROCESSED   STRUCT    -> <Anonymous> Array[1]		tey data (nx,ny)
;   AXES            STRUCT    -> <Anonymous> Array[1]		axis labels
;   NX_CLASS        STRUCT    -> <Anonymous> Array[1]
;   SIGNAL          STRUCT    -> <Anonymous> Array[1]
;   VERSION         STRUCT    -> <Anonymous> Array[1]
;   HEX_XP_INDICES  STRUCT    -> <Anonymous> Array[1]
;   HEX_YP_INDICES  STRUCT    -> <Anonymous> Array[1]


; MODIFICATION HISTORY:
; (25-Nov-18 aph) first version , adapted from h5_read_ptycho.pro
;-

function H5_READ_SGM_IMAGE, silent=silent, tey = tey, struct = struct, io=io, dwell = dwell, $
                             diode=diode, norm=norm, pfya = pfya, pfyr=pfyr, sdd = sdd
@axis_com
@bsif_com
@stack_process_com
COMMON volume_data, image_stack
on_error,2

; determine if AXIS is running (therefore may have called ax_cgo)
; either when AXIS keyword is supplied or if any widget active
if  keyword_set(axis) then axis_on = 1 else axis_on = widget_info(/active)

IF NOT keyword_set(file) then begin
	fltr='*.hdf5'
	file = pickfile2(/READ, FILTER=fltr, /LPATH, DEFPATH=defpath)
ENDIF
s = ''
if file EQ '' THEN RETURN, s  ; bail-out if no filename
check = findfile(file)		 ; bail-out if non-existent file
if strlen(check(0)) EQ 0 then begin
	axis_log, 'Cannot find ' + file
	return, s
endif
; --------- get label from acquisition and construct short name
t = ax_name(file) & fileshort = t(1)

; ----- use h5_browser to examine file and select item
; a=h5_browser(file,/dialog_read)			; first way to do it

; ----- use h5f_parse to open file
tmp= h5_parse(file, /read_data)
sgm_im = tmp.entry1.data

if keyword_Set(struct) then return, sgm_im

; ------------ get photon energy
Energy = sgm_im.en_processed._data

; ----------- get dwell array (NB  dwell at each pixel varies)
clock = sgm_im.clock_processed._data
dwell = mean(clock)/ 1000.
; axis_log, 'dwell (ms) = ' + string(dwell, format='(F7.1)')

; -------- get x & y positions
x_pos = sgm_im.hex_XP_processed._data
y_pos = sgm_im.hex_YP_processed._data
nx = n_elements(x_pos)
ny = n_elements(y_pos)
xl = 'x (um)     E =' + string(energy) + ' eV     dwell (ms) = ' +  string(dwell, format='(F7.1)')

;============ read requested data channels ===============
WIDGET_CONTROL, /Hourglass
if keyword_set(io) OR keyword_set(norm) then begin
; ---------- get Io image data ----
	im_io = sgm_im.io_processed._data
	if keyword_set(io) then begin		; write out Io map
		yl = 'y (um)     SGM image  Io channel'
		dl = fileshort + ' Io'
		tmp = {t:'2d', x: x_pos, y: y_pos, xl: xl, yl: yl, e: energy, d: im_io, dl: dl}
	endif
endif

if keyword_set(dwell) then begin
; ---------- get array of dwell times  ----
	clock = sgm_im.clock_processed._data
	dl_tag = ' clock '
	yl = 'y (um)     SGM image  ' + dl_tag
	dl =  fileshort + ' ' + dl_tag
	tmp = {t:'2d', x: x_pos, y: y_pos, xl: xl, yl: yl,e: energy, d: clock, dl:dl}
endif

if keyword_set(tey) then begin
; ---------- get TEY image data ----
	im_tey = sgm_im.tey_processed._data
	if keyword_set(norm) then begin
		im_tey = im_tey/im_io
		dl_tag = 'TEY/Io'
	endif else	dl_tag = 'TEY'
	yl = 'y (um)     SGM image  ' + dl_tag + ' channel'
	dl =  fileshort + ' ' + dl_tag
	tmp = {t:'2d', x: x_pos, y: y_pos, xl: xl, yl: yl,e: energy, d: im_tey, dl:dl}
endif

if keyword_set(diode) then begin
; ---------- get Transmission image data ----
	im_diode = sgm_im.diode_processed._data
	if keyword_set(norm) then begin
		im_diode = im_diode/im_io
		dl_tag = 'tranmsission/Io'
	endif else	dl_tag = 'tranmsission'
	yl = 'y (um)     SGM image  ' + dl_tag
	dl =  fileshort + ' ' + dl_tag
	tmp = {t:'2d', x: x_pos, y: y_pos, xl: xl, yl: yl,e: energy, d: im_diode, dl:dl}
endif
if keyword_set(pfya) then begin
; --------- get average Fluorscence spectrum (all 4 detectors)
	im_pfy = sgm_im.sdd_processed._data
	fys = fltarr(256)
	for ch = 0, 3 do begin
		for i = 0,255 do fys(i) = fys(i) + mean(im_pfy(ch,i,*,*))
	endfor
	fys = fys/4
	x = findgen(255)
	dl =  fileshort + ' average X-ray fluorescence ' + ' E= ' + string(energy)
	tmp = {t:'1d', x: x, xl: xl, yl:'Average X-ray fluorescence spectrum', dn: fys, d: fys, dl: dl}
endif

if keyword_set(pfyr) then begin
; -------- get average maps for each peak identified in a *-peaks.txt file
	im_pfy = sgm_im.sdd_processed._data
; ----- read in peak positions
	peak_file = pickfile2(TITLE='Peak limit file', /READ, FILTER='*.txt', /LPATH, DEFPATH=defpath)
	peaks = text_read1(peak_file)
	t = size(peaks)
	n_peaks = t(2)
	for i = 0, n_peaks-1 do print, i,  string(peaks(*,i), format='(i3)')		; add element symbol
; ------ read in map from average of all 4 detectors integreated within the peak limits
	WIDGET_CONTROL, /Hourglass
	map_all = fltarr(nx, ny)
	for i = 0, n_peaks-1 do begin
		map = fltarr(nx, ny)		; rset to all 0's for each map
		for ch = 0, 3 do begin
			for j = peaks(0,i), peaks(1,i)-1 do map = map + im_pfy(ch,j,*,*)
		endfor
; ----- generate axis axb format image of PFY data
		dl_tag = 'PFY channel ' + string(i)
		yl = 'y (um)     SGM image ' + dl_tag
		dl =  fileshort + ' ' + dl_tag
		tmp = {t:'2d', x: x_pos, y: y_pos, xl: xl, yl: yl, e: energy, d: map, dl:dl}
; ----- write out map
		q = axb_save(tmp)
		map_all= map_all + map
	endfor
	; ----- generate axis axb format image of PFY data
	dl_tag = 'total FY'
	yl = 'y (um)     SGM image ' + dl_tag
	dl =  fileshort + ' ' + dl_tag
	tmp = {t:'2d', x: x_pos, y: y_pos, xl: xl, yl: yl, e: energy, d: map_all, dl:dl}
endif


ax_wait, /off
return, tmp

end
