; Copyright (c) 1998-2019 A.P. Hitchcock  All rights reserved
;+
;NAME: READ_SOLEIL_PTYCHO
;
;
;LAST CHANGED: ----------------------------------- 	26 Jun 2019

; PURPOSE:
;	This function reads a log file (ascii text) written by python Soleil ptycho acquisition
;
; CATEGORY:
;	    Runs stand alone or inside aXis2000.
;
; CALLING SEQUENCE:

;   RESULT = READ_SOLEIL_PTYCHO(file=file, multiple=multiple, nof=nof, save=save, silent=silent)
;
; INPUTS: none
;
; KEYWORDS:
;	FILE	if set, filename.
;	MULTIPLE  if set, turn on selection of multiple files (useful for stacks)
;   NOF		if set, no filter
;	SAVE	if set, save as axb file
;
; OUTPUTS:
;	structure containing parameters of stxm image derived from ptycho data
;   use along with read_tiff to assemble a fully documented image
;
; COMMON BLOCKS:
; AXIS_COM    stndard set of common blocks
;
; MODIFICATION HISTORY:
; (14-Jun-19 aph) first version
; (21-Jun-19 aph) make self contained & set up for processing multiple (log,tif) files & making stack list file
; (26-Jun-19 aph) float-ed the array read in by read_tif.
;                 as read by read_tif without float, cannot take its log ("arithmetic error: Integer divide by 0")
;-
FUNCTION val_extract, log_line, log_p=log_p
@axis_com
on_error, 2

to = strsplit(log_line, ' ',  /regex, /extract, count=ton)
tag = to(ton-2)
value = to(ton-1)
if keyword_set(log_p) then print, tag, '  =  ',  value

return, value
END



FUNCTION read_soleil_ptycho_log, file=file, nof=nof
@axis_com
on_error, 2

IF NOT keyword_set(file) then begin
	fltr='*.log'
	if keyword_set(nof) then fltr='*'
	file = pickfile2(/READ, title=title, 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


openr,iunit,file,/get_lun

t = ''
readf, iunit, t
dark = val_extract(t)
readf, iunit, t
datafile = val_extract(t)
readf, iunit, t
pixfile = val_extract(t)
readf, iunit, t
CentreX  = float(val_extract(t))
readf, iunit, t
CentreY =  float(val_extract(t))
readf, iunit, t
dwell =  float(val_extract(t))
readf, iunit, t
energy =  float(val_extract(t))
readf, iunit, t
image_shape = val_extract(t)

; --------  read rest of log file
rest = ''
while ~ EOF(iunit) do begin
	readf, iunit, t
	rest = rest + t
endwhile

; ----- close and free iunit
close, iunit & free_lun, iunit

xstart = strpos(rest, '[')
xstop = strpos(rest, ']')
xs = strmid(rest, xstart+1, xstop - xstart)
x = float(strsplit(xs, ' ',  /regex, /extract, count=ton))
; print, x

ystart = strpos(rest, '[', xstop)
ystop = strpos(rest, ']', ystart+1)
ys = strmid(rest, ystart+1, ystop - ystart)
y = float(strsplit(ys, ' ',  /regex, /extract, count=ton))
; print, y

nstart = strpos(datafile, 'SI')			; set up for SI (images),  SS (stacks)
nstop = strpos(datafile, '_', nstart)
dl_nxs = strmid(datafile, nstart,nstop-nstart)
; print, nstart, nstop, dl_nxs

nstart = strpos(pixfile, '_', /reverse_search)
nstop = strpos(pixfile, '.hdf5')
dl_pix = strmid(pixfile, nstart+1,nstop-nstart-1)
; print, nstart, nstop, dl_pix


dl = 'nxs:' + dl_nxs + '  pix: ' + dl_pix
; print, dl

; put variables into a IDL structure
t = {dwell:dwell, energy:energy, x:x, y:y, dl:dl}
;
return, t

end


FUNCTION read_soleil_ptycho, file=file, nof=nof, save=save
@axis_com
on_error, 2
; ------------------ shell for reading tif and managing multipe file processing
s= ''

if not keyword_set(file) then begin
		ptif_file = dialog_pickfile(filter='*.tif', title='select one or more tif files (STXM or ptycho)', $
		          PATH=LPATH, GET_PATH=defpath, /multiple_files)
		if defpath NE lpath then lpath= defpath
endif else ptif_file = file

stacklist=strarr(n_elements(ptif_file))		; array for names of files to go into stack list

for i = 0, n_elements(ptif_file)-1 do begin
;	print, 'File to strip: ', ptif_file(i)
	t =ax_name(ptif_file(i))
	nstop = strpos(ptif_file(i), '_')
	nstop2 = strpos(ptif_file(i), '_',nstop+1)		; find position of second '_'
;	print, nstop, nstop2
	log_file =  strmid(ptif_file(i), 0,nstop2) + '.log'     ; for stacks SS74_20190614nrj06.log  or images  SI14_20190617.log
														; for SI10_20190617_prepro_AMP.tif  with log  SI10_20190617.log

;	print, 'Opening log file: ', log_file

	log = read_soleil_ptycho_log(file=log_file)
	t =ax_name(ptif_file(i))
	tif_type = strmid(ptif_file(i), nstop2+1, (strpos(ptif_file(i),'.') - nstop2-1))
;	print,' type is ',  tif_type
	IF n_tags(log) EQ 0 THEN BEGIN
	 	print, 'cannot find ',log_file
		return, s   ; bail if cannot find log file
	ENDIF

	x = log.x  &  y = log.y
	t_tif = float(read_tiff(ptif_file(i)))
	t = size(t_tif)
	nx_tif = t(1)  & ny_tif = t(2)
	; ------- match # of x, y points to size of the reconstructed image
	;	print, 'BEFORE: ', x
	IF nx_tif NE n_elements(log.x) then begin
		x = findgen(nx_tif)
		x_step = (log.x(n_elements(log.x)-1) - log.x(0) )/ nx_tif
		x = log.x(0) +x*x_step
		y = findgen(ny_tif)
		y_step = (log.y(n_elements(log.y)-1) - log.y(0) )/ ny_tif
		y = log.y(0) +y*y_step
	ENDIF
	;	print, 'AFTER: ', x
	xl = string(log.energy,log.dwell, $
	            format='("x (um) E =",f7.2," eV   Dwell =",f6.2," ms ")')
	yl = 'y (um) ' +  tif_type
	tmp = {t:'2d', x:x, y:y, E: log.energy, d:t_tif, $
			       xl:xl, yl:yl, dl:log.dl + ' ' + tif_type }
	t=ax_name(ptif_file(i))
;	axis_log, tif_type + ' image  read from ' + t(1)

	; --------  optional save file -----------
	if keyword_set(save) then begin
		t = ax_name(ptif_file(i))
		if n_elements(ptif_file) GT 1 then begin
			t_ind = '_'+ strtrim(string(i+1),2)
;			print, '|',t_ind, '|'
		endif else t_ind = ''
		fname = t(0) + strmid(t(1), 0, 4) + tif_type + t_ind +'.axb'

		t = axb_save(tmp, file=fname)
;		print, 'saved ', fname

	; ---- update SL file
		t = ax_name(fname)
		sl_new = string(t(1) + '.' + t(2))
		stacklist(i) = sl_new
	endif
ENDFOR

; -------- write stack list file
if keyword_set(save) then begin
	t = ax_name(ptif_file(0))
	sl_file = t(0) + strmid(t(1), 0, 4) +  '_' + tif_type + '.sl'
	openw,iunit,sl_file,/get_lun
	printf, iunit, t(0)
	for i = 0, n_elements(stacklist)-1 do begin
		printf, iunit, stacklist(i)
	endfor
	close, iunit & free_lun, iunit
	t=ax_name(sl_file)
	axis_log, 'stack list = ' + sl_file
endif

return, tmp		; only last image of multiple file read is sent to aXis2000

end
