; Copyright (c)2006-2014   A.P. Hitchcock  All rights reserved
;+
;NAME:
;			READ_ALL.PRO
;
;LAST CHANGED: ----------------------------------- 22-Feb-06 (aph)
;
; PURPOSE:
;   This function reads ion-ion correlation data from Time-of-Flight measurements
; performed and written by pTA program (C++, Neville)
;
; CATEGORY:
;	utility; stand-alone or used through axis2000
;
; CALLING SEQUENCE:
; for functions:
;	Result = ReadAll (file=file, pipico=pipico, axis_on=axis_on, silent=silent, energy=energy)
;
; INPUTS: none obligatory
;
; KEYWORDS:
; FILE		filename
; PIPICO  	plot PIPICO to check quality
; AXIS_ON   if set, called from aXis2000
; SILENT	d not prompt for parameters
; ENERGY	energy of all file
;
; OUTPUTS:
;	Result is an aXis2000 format image of the PEPIPICO signal
; based on user-selected binning parameters
;
; COMMON BLOCKS:
;	AXIS_COM	standard set of common blocks
;
; MODIFICATION HISTORY:
; (14-feb-04 aph) first version
; (21-feb-04 aph) adapt for auto use in all-sequence conversion
; (22-feb-06 aph) correct to use long's for large data sets
; (21-Jul-14 aph) corrected header

;-

Function Read_All, file=file, pipico=pipico, axis_on=axis_on, silent = silent, energy=energy
@axis_com
on_error,2

; determine if AXIS is running
; either when AXIS parameter in ax_peem_com is set or if any widget active
if not keyword_set(axis_on) then begin
	axis_on = widget_info(/active)
	if axis_on EQ 0 then axis_ID = 0
endif

; select and open binary "*.all' file
IF NOT keyword_set(file) then begin
	file = pickfile2(filter='*.all', /READ, /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
	text =  'Cannot find ' + file
	print, text
	widget_control, Bad_ID=Bad_ID, Uprompt, SET_VALUE=text
	return, s
endif
t = ax_name(file)
fileshort = t(1)
openu, iunit, file, /get_lun , /binary, /noautomode

; read data
if NOT keyword_set(silent) then print, 'Reading ALL correlated stops file: ',  fileshort
NumCorrStops = ulong(0)
MaxStops = long(0)
BinWidth = 0.
Offset = 0.
readu, iunit, NumCorrStops
if NOT keyword_set(silent) then print, 'Number of correlated stops = ', NumCorrStops
readu, iunit, MaxStops
if NOT keyword_set(silent) then print, 'Max stops = ', MaxStops
readu, iunit, BinWidth
if NOT keyword_set(silent) then print,  'BinWidth (ns) = ', BinWidth*1.e6
readu, iunit, Offset
if NOT keyword_set(silent) then print, 'Offset (ns) = ', Offset*1.e6
; print, 'time interval (us) = ', Offset/BinWidth, ' to ', BinWidth*1024 + Offset/BinWidth

all0 = intarr(NumCorrStops)
all1 = lonarr(NumCorrStops)
all = lonarr(NumCorrStops)

mumbo = long(0)
time = long(0)
stopnum = 0

; (from John Neville (10-Feb-04)
;  32-bit integer is composed of
;  top 8-bits = stop number -1
;  bottom 24-bits = time with tic size of BinWidth
readu, iunit, mumbo
stopnum = ishft(mumbo,-24)+1
all0(0) = stopnum
time = 	ishft(mumbo,8)/256		; initially /64 but times x4 too large; so shift to /256
all1(0) = time					; should be 256 = 2^8 !!
all(0) = mumbo
pip = lonarr(1)
j = 0L
for i = 1L, NumCorrStops-1 do begin
	readu, iunit, mumbo
	all(i) = mumbo
	stopnum = ishft(mumbo,-24)+1
	all0(i) = stopnum
	time = 	ishft(mumbo,8)/256
	all1(i) = time
;	print, stopnum, time
; generate PIPICO as fast check
	if stopnum EQ 2 then begin
		pip(j) = time - all1(i-1)
		j = j + 1
		pip = [pip,0]
	endif
endfor
close, iunit
free_lun, iunit

; convert times to absolute time in microseconds
time = fltarr(NumCorrStops)
time = float(all1)*BinWidth ;+ Offset*1e6
; print, 'times - min, max ',min(time), max(time)

; get or set energy
if NOT keyword_set(silent) then begin
	IF keyword_set(energy) then begin
		tofE = energy
	endif else begin
		if axis_on then begin
			tofE = get_num(prompt = 'Photon Energy (eV) ', val = tofE, group = axis_id)
		endif else begin
		    tofE = get_num(prompt = 'Photon Energy (eV) ', val = tofE)
		endelse
	endelse
endif

; plot histogram of pipico using plausible binning
if keyword_set(pipico) then begin
	pip = float(pip) * Binwidth
	x = findgen(256)*max(time)/256
	temp = histogram(pip, binsize = x(1)- x(0))
	if axis_on then begin
		tmp = {t: '1d', x: x, d: temp, dn: temp, e: tofE, $
		        xl: string(format='("del-TOF      E = ",F8.2," eV")',tofE), $
		        yl: 'PIPICO', dl: 'PIPICO of ' + fileshort}
		HANDLE_VALUE, Data(Curbuf), tmp, /SET
		Label(CurBuf) = tmp.dl
		PlotBuf, CurBuf
		CurBuf = CurBuf + 1
		If CurBuf GT 9 then CurBuf = 0
	endif else 	plot, x, temp
endif

; generate 2-d data with selected binning
if NOT keyword_set(silent) then begin
	if axis_on then begin
		if stop1 EQ 0 then stop1 = 1
		if stop2 EQ 0 then stop2 = 2
		if bin_ns EQ 0    then bin_ns = floor(BinWidth*1.e6) + 1
		if tof1_max EQ 0  then tof1_max = max(time)
		if tof2_max EQ 0  then tof2_max = max(time)
		stop1 = get_num(prompt = 'First Stop # ', val = stop1, group = axis_id)
		stop2 = get_num(prompt = 'Second Stop # (>First Stop #) ', val = stop2, group = axis_id)
		bin_ns = get_num(prompt = 'time bin (ns) '+ string(format='("recorded at ",i3)',floor(BinWidth*1.e6)+1), $
		            val = bin_ns, group = axis_id)
		tof1_min = get_num(prompt = 'TOF 1: minimum (0) ', val = tof1_min, group = axis_id)
		tof1_max = get_num(prompt = 'TOF 1: maximum ('+	string(format='("data max= ",f5.1)',max(time))+')', $
		             val = tof1_max, group = axis_id)
		tof2_min = get_num(prompt = 'TOF 2: minimum (0)', val = tof2_min, group = axis_id)
		tof2_max = get_num(prompt = 'TOF 2: maximum ('+	string(format='("data max= ",f5.1)',max(time))+')', $
		             val = tof2_max, group = axis_id)
	endif else begin
		stop1 = 1
		stop2 = 2
		bin_ns = floor(BinWidth*1.e6) + 1
		tof1_min = 0.
		tof1_max = max(time)
		tof2_min = 0.
		tof2_max = max(time)
		tofE = 0
		stop1 = get_num(prompt = 'First Stop # ', val = stop1)
		stop2 = get_num(prompt = 'Second Stop # (>First Stop #) ', val = stop2)
		bin_ns = get_num(prompt = 'time bin (ns) '+ string(format='("recorded at ",i3)',floor(BinWidth*1.e6)+1), $
		            val = bin_ns)
		tof1_min = get_num(prompt = 'TOF 1: minimum ', val = tof1_min)
		tof1_max = get_num(prompt = 'TOF 1: maximum ', val = tof1_max)
		tof2_min = get_num(prompt = 'TOF 2: minimum ', val = tof2_min)
		tof2_max = get_num(prompt = 'TOF 2: maximum ', val = tof2_max)
	endelse
endif

bin_us = bin_ns/1000.
ntof1 = fix((tof1_max - tof1_min)/bin_us)
ntof2 = fix((tof2_max - tof2_min)/bin_us)
tof1 = findgen(ntof1)*bin_us + tof1_min
tof2 = findgen(ntof2)*bin_us + tof2_min
;print, 'number of bins ', ntof1, ' * ', ntof2
;print, 'tof1: ', tof1(0), ' to ', tof1(ntof1-1)
;print, 'tof2: ', tof2(0), ' to ', tof2(ntof2-1)

; bin times into user selected format
pepipico = intarr(ntof1, ntof2)
corrnum = 0
for i = 0L, NumCorrStops-(stop2-stop1)-1 do begin
	if all0(i) EQ stop1 AND time(i) GE tof1_min AND time(i) LE tof1_max then begin
		for j = i+1, (i + stop2 - stop1) do begin
			if all0(j) EQ stop2 AND time(j) GE tof2_min AND time(j) LE tof2_max then begin
				ix = fix((time(i)-tof1_min)/bin_us)-1
				iy = fix((time(j)-tof2_min)/bin_us)-1
;				print,'ix= ', fix(ix),' iy= ',fix(iy)
				pepipico(ix,iy) = pepipico(ix,iy) + 1
				corrnum = corrnum + 1
			endif
		endfor
	endif
endfor
if NOT keyword_set(silent) then begin
	text = 'Number of correlated stops in range = ' + string(Corrnum)
	if axis_on then Widget_control, Bad_ID=Bad_ID, Uprompt, SET_VALUE=text
	print, text
endif

; generate image of pepico
all2d = {t: '2d', x: tof1, xl: string(format='("TOF ",i1,"    E = ", F8.2," eV")', stop1,tofE), $
         y: tof2, yl: string(format='("TOF ",i1)', stop2), $
         d: float(pepipico), dl: 'PEPIPICO from ' + fileshort, e: tofE }
; help, all2d, /struct
if not axis_on AND not keyword_set(silent) then splot2d, all2d

if axis_on then scale_bar = 0

return, all2d

end
