; assemble stack from tif - special for pySTXM no *.hdr file

; (19-Jul-2019 aph)

FUNCTION make_stack
@stack_process_com
@axis_com
@bsif_com
COMMON volume_data, image_stack

cd,'Z:\data\XRM\CLS-cryo-STXM\2019\19-07\07-11\C190711022\rescue'

; ---------- get x,y values
f = 'Z:\data\XRM\CLS-cryo-STXM\2019\19-07\07-11\C190711022\rescue\C190711022_xy.txt'
openr, iunit, f, /get_lun
x = fltarr(1)
y = fltarr(1)
while not eof(iunit) do begin
	readf, iunit, xt, yt
	x = [x, xt]
	y = [y,yt]
endwhile
x = x(1:n_elements(x)-1)
y = y(1:n_elements(y)-1)
close, iunit & free_lun, iunit


tmpf = DIALOG_PICKFILE(/Read, FILTER='*.tif',/multiple, $
     title = 'Select tif files in the stack') ; , /LPATH, DEFPATH=defpath)
filename_list = tmpf(sort(tmpf))
n_files = n_elements(filename_list)

; ---------- edit filenames to get energy
ev = fltarr(n_files)
;print, tmpf(0)
for i = 0, n_files-1 do begin
	t=ax_name(filename_list(i))
	n=t(1)
;	print, n
	last =strpos(n,'_', /reverse_search)
;	print, last
	n2=strmid(n, 0, last)
;	print, n2
	last2=strpos(n2,'_', /reverse_search)
;	print, last2
	ev(i)=float(strmid(n2, last2+1))
;	print, ev(i)
endfor

; -------  construct image_stack
nx = n_elements(x)
ny = n_elements(y)

image_stack = findgen(nx,ny,n_files)
; help, image_stack

; -------- get data
x_stop = x(nx-1)
x_start = x(0)
y_stop = y(ny-1)
y_start = y(0)
filename_ev_msec_list = strarr(n_files)

for i = 0, n_files-1 do begin
	tmp = img_load(file = filename_list(i), /TIF, /VALUES)
;	help, tmp, /struct
;	d = reform(image_stack(*,*,i))
	td = congrid(tmp.d, nx, ny, /interp, cubic=-0.5)
	image_stack(*,*,i) = td
	t = ax_name(filename_list(i))
	filename_ev_msec_list(i) = t(1) + '  ' + string(ev(i), format = '(F7.2)') + '   1.00 ms'
endfor


; -------  write (*.ncb, dat)

filename = pickfile2(filter = '*.ncb', file = filename, title = 'binary stack file ')
if strlen(filename) GT 0 then begin
	t = ax_name(filename)
	filename = t(0) + t(1) +'.ncb'
	stack_wb, filename
endif else return, 'did not write stack ' + filename      ; filename='stack.ncb' PRIOR to 28-Aug-13, if canceled, gave problems

return, filename

END