; Copyright (c) 1998-2021 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	READ_SGM_SPECTRA
;
;LAST CHANGED: ----------------------------------- 02 May 2021 (aph)
;
;PURPOSE:
;	This function reads  data  from an hdf5 file written by CLS SGM
; TEY, Io, clock, photodiode, and partial (or total FY can be read
; the SDD spectrum is displayed during read-in so the user can identify the limits for the peak of interest
;
;CATEGORY:
;	STAND ALONE or called in aXis2000:  spectral processing
;
;CALLING SEQUENCE:
; 	s = read_sgm(file=file,nof=nof, struct_only=struct_only, silent=silent)
;
;CALLED FROM AXIS:
;	Read~spectrum~SGM
;
;INPUTS: none
;
;KEYWORDS:
;   struct_only	= read & return structure
;	file		= name of file (if not in ncall, will launch dialog)
;	nof	= no name filter
;	silent		= do not print progress

;OUTPUTS:
;    returns spectrum
;
;COMMON BLOCKS:
;	axis_com
;
;MODIFICATION HISTORY:
; (26-Feb-21 aph) first version
; (02-Mar-21 aph) add read-in of user-selected FY spectra
; (02-May-21 aph) fix up on-the-fly sum (was returning NaN error) ==> code bad from 2-MArch to 2-May 2021 !!!!
;-

FUNCTION read_sgm,file=file,nof=nof, struct_only=struct_only, silent=silent

@axis_com
@sgm_com

on_error,2

; get filename if not supplied in call
fltr='*.hdf5'
if keyword_set(nof) then fltr='*'
title = 'Select SGM hdf5 data file'
if not keyword_set(file) then file = pickfile2(/READ, FILTER=fltr, /LPATH, DEFPATH=defpath, TITLE = TITLE)
; print, 'File to open is ', file
if strlen(file) EQ 0 THEN RETURN, 0

; use h5_parse to get data as an IDL structure
t = ax_name(file)  & fileshort = t(1)
if NOT keyword_set(silent) then print, 'Reading from file ', fileshort
a=h5_parse(file,/read_data)

; --- return the structure
IF keyword_set(struct_only) THEN RETURN, a


; ------- CHOOSE TYPE OF DATA to read
if n_elements(sgm_type) EQ 0 then sgm_type = 'T'

if widget_info(/active) EQ 0 then $
	sgm_type = get_text(prompt = '<T>ey, <I>o, <C>lock,<P>hotodiode, <F>luorescece yield', val=sgm_type) $
	else $
		sgm_type = get_text(prompt = '<T>ey, <I>o, <C>lock,<P>hotodiode, <F>luorescece yield', val=sgm_type, group = aXis_ID)
sgm_type=strmid(sgm_type,0,1)
sgm_type =strupcase(sgm_type)

; ---------- get energy  NB first point reads as NaN so remove it
	ev = reform(a.entry1.data.en._data)
	ev = ev(1:n_elements(ev)-1)

CASE sgm_type OF

'T': BEGIN
	;  --------- get the TEY data
	tey = reform(a.entry1.data.tey._data)
	tey = tey(1:n_elements(tey)-1)
	; -------- construct spectral file
	dl = fileshort + ' tey'
	tey={t:'1d', d:tey, x: ev, xl: 'Energy (eV)', dn: tey, dl: dl }
	axis_log, 'SGM TEY spectrum read from ' + fileshort

	return, tey
	END

'I': BEGIN
	;  --------- get the I0  data
	tey = reform(a.entry1.data.I0._data)
	tey = tey(1:n_elements(tey)-1)
	; -------- construct spectral file
	dl = fileshort + ' I0'
	io={t:'1d', d:tey, x: ev, xl: 'Energy (eV)', dn: tey, dl: dl }
	axis_log, 'SGM I0 spectrum read from ' + fileshort

	return, io
	END

'C': BEGIN
	;  --------- get the CLOCK data
	tey = reform(a.entry1.data.clock._data)
	tey = tey(1:n_elements(tey)-1)
	; -------- construct spectral file
	dl = fileshort + ' clock (s)'
	clock={t:'1d', d:tey, x: ev, xl: 'Energy (eV)', dn: tey, dl: dl }
	axis_log, 'SGM CLOCK signal read from ' + fileshort

	return, clock
	END

'P': BEGIN
	;  --------- get the Photodiode data
	tey = reform(a.entry1.data.PD._data)
	tey = tey(1:n_elements(tey)-1)
	; -------- construct spectral file
	dl = fileshort + ' photodiode '
	pd={t:'1d', d:tey, x: ev, xl: 'Energy (eV)', dn: tey, dl: dl }
	axis_log, 'SGM photodiode signal read from ' + fileshort

	return, pd
	END


'F': BEGIN

	if n_elements(ssd_ch) EQ 0 then ssd_ch = 'A'
	if widget_info(/active) EQ 0 then $
	ssd_ch = get_text(prompt = 'SDD<1>,SDD<2>,SDD<3>,SDD<4> or <A>vg', val=ssd_ch) $
	else $
		ssd_ch = get_text(prompt = 'SDD<1>,SDD<2>,SDD<3>,SDD<4> or <A>vg', val=ssd_ch, group = aXis_ID)
	ssd_ch=strmid(ssd_ch,0,1)

;	----------- read average SDD spectrum for requested SDD
	CASE ssd_ch OF

	'1':	sdd = a.entry1.data.sdd1._data
	'2':	sdd = a.entry1.data.sdd2._data
	'3':	sdd = a.entry1.data.sdd3._data
	'4':	sdd = a.entry1.data.sdd4._data
	ELSE: BEGIN
			sdd = a.entry1.data.sdd1._data
			sdd = sdd + a.entry1.data.sdd2._data
			sdd = sdd + a.entry1.data.sdd3._data
			sdd = sdd + a.entry1.data.sdd4._data
			sdd = sdd/4
		  END
	ENDCASE

	t = size(sdd)
	n_x = t(1)
	n_e = t(2)
	x = 10*findgen(n_x)			; convert from channel # to X-ray emission energy (10 eV/channel)
	sum = fltarr(n_x)

; -------- replace NaN values with 0
	sdd_nan = where(~FINITE(sdd), count)
	if count GT 0 then sdd(sdd_nan)=0.

; -------- integrate SDD spectrum recorded at each photon energy
	for i = 1, n_e - 1 do begin
		sum = sum + sdd(*,i)
	endfor

	; -------- construct SDD X-ray fluorescence file
	dl = fileshort + ' SDD ' + ssd_ch
	f={t:'1d', d:sum, x: x, xl: 'channel', dn: sum, dl: dl }
;	axis_log, 'SDD '+ ssd_ch + ' average fluorescence  read from ' + fileshort

;	return,f
	if widget_info(/active) EQ 0 then begin
		splot, f
	endif else begin
		CurBuf_tmp = CurBuf
		HANDLE_VALUE, Data(0), f, /SET
		Label(0) = f.dl
		PlotBuf, 0
		CurBuf = CurBuf_tmp
	endelse

; ---------  plot and ask user to select X-ray emission energy integration limits
	if n_elements(ch_lo) EQ 0 then E_lo  = 10 else E_lo=ch_lo*10
	if widget_info(/active) EQ 0 then $
		E_lo = fix(get_num(prompt='X-ray E: lower limit', val=E_lo)) $
		else  E_lo = fix(get_num(prompt='X-ray E: lower limit', val=E_lo, group = axis_ID))
	if n_elements(ch_hi) EQ 0 then ch_hi= 10*(n_x - 1) else E_hi=ch_hi*10
	if widget_info(/active) EQ 0 then $
		E_hi = fix(get_num(prompt='X-ray E: upper limit', val=E_hi)) $
			else E_hi = fix(get_num(prompt='X-ray E: upper limit', val=E_hi, group = axis_ID))
	ch_lo = E_lo / 10		; convert back to channel #
	ch_hi = E_hi / 10

; --------- integrate over user selected limits
	print, 'Integrating SDD signal from ', E_lo,' to ', E_hi
	fy = fltarr(n_e-1)
	for i = 0, n_e-2 do begin
		fy(i) = reform(total(sdd(ch_lo:ch_hi,i)))
	endfor

; -------- construct spectral file
	if ssd_ch EQ 'A' then tl = 'Average' else tl = ssd_ch
	dl = fileshort + ' PFY from SDD ' + tl + '  I: ' + string(10*ch_lo, format='(I4)') + ' - ' + string(10*ch_hi, format='(I4)')
	t= reform(a.entry1.data.en._data)
	ev = t(1:n_e-2)
	fy = fy(1:n_elements(fy)-1)
	tmp = {t:'1d', d: fy, x: ev, xl: 'Photon energy (eV)', dn: fy, dl: dl }

	axis_log, 'SDD '+ tl + ' partial fluorescence yield read from ' + fileshort

	return,tmp

	END


ELSE: print, 'invalid data identifier'


ENDCASE

END
