; Copyright (c) 1998-2009 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	AX_CONV_TOF-ALL
;
;LAST CHANGED: ----------------------------------- 30-jul-09
;
;PURPOSE:
;	This function convert a sequence of ALL correlated time-of-flight files
; to  axis binary file format. Optional binning for smoothing.
;
;CATEGORY:
;	AXIS: stack analysis
;
;CALLING SEQUENCE:
; for functions:
;	Result = AX_CONV_ALL(AXIS_ON=AXIS_ON)
;
;CALLED FROM AXIS:
;	->Stacks->convert format->TOF-ALL

;INPUTS: none
;
;KEYWORDS:
; AXIS_ON   if set, called from aXis2000
;
;OUTPUTS:
;	*.ncb
;
;COMMON BLOCKS:
;	AXIS_COM	standard set of common blocks
;   stack_process_com     stack_process common
;	BSIF_COM	common for netCDF format data
; 	VOLUME_DATA  image_stack 3-d array
;
;PROCEDURE:
;
;EXAMPLE:
;
;MODIFICATION HISTORY:
; (14-feb-04 aph) adapted from AX_CONV
; (21-feb-04 aph) working in aXis2000; optional Io normalization; save PIPICO(1)
; (30-jul-09 aph) changed analcom to stack_process_com (NB STILL need to convert stack_analyze_tof !!)
;-

FUNCTION ax_conv_all, AXIS_ON=AXIS_ON
@axis_com
@stack_process_com
COMMON volume_data, image_stack
@bsif_com
on_error,2

if NOT keyword_set(axis_on) then axis_on=0

WIDGET_CONTROL, Uprompt, BAD_ID = BadID, SET_VALUE='pick first file of sequence'
file1=PICKFILE2(/Read, FILTER='*a.*', /LPATH, DEFPATH=defpath)
if strlen(file1) EQ 0 THEN Return, 0
WIDGET_CONTROL, Uprompt, BAD_ID = BadID, SET_VALUE='pick last file of sequence'
file2=PICKFILE2(/Read, FILTER='*a.*', /LPATH, DEFPATH=defpath)
if strlen(file2) EQ 0 THEN Return, 0
; assumes the sequence of ALL files are a name with extension giving the sequence number
; and that a spectral file exists with energies of each image
t = ax_name(file1)
fileroot=t(0) + t(1)
fileshort=t(1)
first = fix(t(2))
t = ax_name(file2)
last  = fix(t(2))
print, 'AX_CONV_ALL:  converting ALL correlated event file sequence'
print,'    ', fileroot, fileshort,'   from ', first, ' to ', last

; Read energies & Io file
WIDGET_CONTROL, Uprompt, BAD_ID = BadID, SET_VALUE='pick energy & Io file'
Efile=PICKFILE2(/Read, FILTER='*.ty', /LPATH, DEFPATH=defpath)
if strlen(Efile) EQ 0 THEN Return, 0
openr, iunit, Efile, /get_lun
tmp = ' '

; obtain dwell time
while strpos(tmp,'dwell') EQ -1 do begin
	readf, iunit, tmp
	print, tmp
endwhile
num_start = strpos(tmp, 'dwell') + 6
num_end =  strpos(tmp, ' ', num_start)
dwell = float(strmid(tmp,num_start, num_end-num_start+1))/1000
print, 'dwell (s) = ', dwell

; obtain energies
while strpos(tmp,'energies') EQ -1 do begin
	readf, iunit, tmp
	print, tmp
endwhile
num_start = strpos(tmp, '= ')
num_end =  strpos(tmp, ' ', num_start+2)
num = fix(strmid(tmp,num_start+1, num_end-num_start))
print, 'Energy file contains ', fix(num), ' energies'
;skip header for data
readf, iunit, tmp
print, tmp
energy = fltarr(num)
Io = fltarr(num)
for i = 0, num-1 do begin
	readf, iunit, tmp
	blank = strpos(tmp,' ')
	energy(i) = float(strmid(tmp,0,blank))
	tmp = strtrim(strmid(tmp,blank),1)
	blank = strpos(tmp,' ')
	Io(i) = float(strmid(tmp,0,blank))
;	print, i, energy(i), '  ', Io(i)
endfor
close, iunit


;store or plot Io spectrum if user wishes
if dialog_message('Plot Io specrum ?', /question) EQ 'Yes' then begin
	tmp = {t: '1d', x: energy, xl: 'E (eV)', d: Io, dn: Io, dl: 'Io from ' + fileshort}
	if axis_on then begin
		HANDLE_VALUE, Data(Curbuf), tmp, /SET
		Label(CurBuf) = tmp.dl
		PlotBuf, CurBuf
		CurBuf = CurBuf + 1
		If CurBuf GT 9 then CurBuf = 0
	endif else splot, tmp
endif

if dialog_message('Normalize to Io spectrum ?', /question) EQ 'Yes' then $
   normIo = 1 else normIo = 0

; Insert pressure read and normalization code here


WIDGET_CONTROL, Uprompt, BAD_ID = BadID, SET_VALUE= 'reading in ALL sequence'
; set conversion parameters from first file
tmp = read_all(file=file1, /pipico, axis_on=axis_on, energy = energy(0))

npts = last - first + 1
nx = n_elements(tmp.x) & ny = n_elements(tmp.y)
n_cols = nx & n_rows = ny
image_stack = fltarr(nx,ny,npts)
filename_ev_msec_list = strarr(npts)
;	print, 'Dimension of volume data is ', nx, ny, npts

; read sequence and construct stack
; note first , last are on number scale starting with 1, but
; energy, Io indices are on number scale starting with 0
for i_file = first, last do begin
	num = strcompress(string(1000 + i_file))
	num = strmid(num,2,4)
	file=fileroot + '.' + num
	tmp = read_all(file=file, axis_on=axis_on, /silent)
	if normIo then tmp.d = tmp.d / Io(i_file-1)
	image_stack(*,*,i_file-first) = tmp.d
	filename_ev_msec_list(i_file-first) = num + ' ' + $
	    string(energy(i_file-1), format = '(F7.2)') + '  ' +  string(dwell, format='(F4.0)')
	text = string(energy(i_file-1), format="('TOF ALL stack ',/,'E= ',f8.3)")
	if axis_on then WIDGET_CONTROL,UPrompt, Bad_ID = badID, SET_VALUE=text else $
		print, 'Read_All: E =', string(energy(i_file-1),format='(F8.2)'), ' eV.  ', strcompress(file)
endfor

; write stack
widget_control,hourglass=1
filename = fileroot +'.ncb'
filename = pickfile2(filter='*.ncb', lfile=filename, /READ, /LPATH, DEFPATH=defpath)
x_start = tmp.x(0) & x_stop = tmp.x(n_elements(tmp.x)-1)
y_start = tmp.y(0) & y_stop = tmp.y(n_elements(tmp.y)-1)
ev = energy(first-1:last-1)
; reverse data if in wrong order
if energy(last-1) LT energy(first-1) then begin
	test = dialog_message(/question, 'Energies out of order. Sort ?')
	if test EQ 'No' then goto, end_ev_sort
	sort_ev = sort(ev)
	timg = image_stack
	tlbl = filename_ev_msec_list
	for i = 0,n_elements(ev)-1 do begin
		image_stack(*,*,i) = timg(*,*,sort_ev(i))
		filename_ev_msec_list(i) = tlbl(sort_ev(i))
	endfor
	ev = ev(sort(ev))
endif
end_ev_sort:
stack_wb, filename
widget_control,hourglass=0
s = filename		; return name of stack file for read-in to zimba
t = ax_name(s)
text = 'Sequence of ALL files => stack ' + t(1)
if axis_on then WIDGET_CONTROL,UPrompt, Bad_ID = badID, SET_VALUE=text
print, text

return, s
end
