	; Copyright (c) 1998-2012 A.P. Hitchcock  All rights reserved
;+
;NAME: STACK2_RB
;
;LAST CHANGED: ----------------------------------- 20-Feb-12
;
; PURPOSE:
;  This function reads a stack-of-stacks - I(x,y,SRF-E,a,b)
;  where a = fluorescence X-ray energy,
;        b = additional control parameter (e.g. incident photon energy)
;
; CATEGORY:
;	stack-of-stack processing; stand alone operation
;
; CALLING SEQUENCE:
;	STACK2_RB( [, FILE=FILE, SILENT=SILENT ]
;
; INPUTS:
;
; KEYWORDS: none
; 	FILE	name of the input file
;	SILENT	if set, no print
;
; OUTPUTS:
; 	returns set of control variables in a 1-d array
;	xas_xrf_stack in common blokc volume_data2
;
; COMMON BLOCKS:
; AXIS_COM	standard set of common blocks
; STACK_PROCESS_COM
; BSIF_COM
; volume_data, image_stack
; volume_data2, xas_xrf_stack
;
; DETAILS:
;  Unformatted 4d array is read from a binary file - writted in Windows format.
;  May need to worry about Endian (byte order) differences between Unix and Win
;  Scales are extracted from the associated *.dat file
;  Data is transferred to other programs via Common volume2_data, xas_xrf_stack

; SIDE EFFECTS:
;
; RESTRICTIONS: none
;
; MODIFICATION HISTORY:
; (21-Feb-10 aph) first version
; (20-Feb-12 aph)

FUNCTION STACK2_RB, file=file, silent=silent
@axis_com		; include COMMON from file
@stack_process_com
COMMON volume_data, image_stack
COMMON volume_data2, xas_xrf_stack
@bsif_com
on_error,2

if n_elements(file) eq 0 then begin
	fltr='*.ssb'
	if keyword_set(nof) then fltr='*'
	file = pickfile2(/READ, FILTER=fltr, /LPATH, DEFPATH=defpath)
ENDIF

; ------  read header file
t = ax_name(file)
fileshort = t(1)
E_file = t(0)+t(1)+'.dat'
openr, iunit, E_file, /get_lun

; ---- read dimensions of image and each stack
readf,iunit, nx, ny, npts, scale
; print, nx, ny, npts, scale
readf, iunit, x_start, x_stop
readf, iunit, y_start, y_stop
; print, 'X: ', x_start, x_stop, 'Y: ', y_start, y_stop

; read X-ray fluorescence energies (same for each stack)
ev = fltarr(npts)
; print, 'reading X-ray fluorescence spectral energies (or channels)'
text = ''
readf, iunit, text
readf, iunit, ev

; read 4th-axis values (e.g. incident photon energies)
; print, 'Reading control variable values (e.g. incident photon energies)'
readf, iunit, text
readf, iunit, n_stacks
ph_E = fltarr(n_stacks)
readf, iunit, ph_E
; print, ph_E

; read labels of each stack
; print, 'reading labels '
readf, iunit, text
filename_ev_list = strarr(n_stacks)
readf, iunit, filename_ev_list
FILENAME_EV_MSEC_LIST = filename_ev_list
; print, filename_ev_list

close, iunit
free_lun, iunit

; -------- define dimension of xas_xrf_stack
xas_xrf_stack = intarr(nx,ny,npts,n_stacks)

; --------- read data (integer !) ----------------
ax_wait
openu, iunit, file, /get_lun
readu, iunit, xas_xrf_stack
close, iunit
free_lun, iunit
ax_wait, /off

if not keyword_set( silent) then $
     axis_log, ' Binary 4-d file (STACK of STACKS) read from ' + fileshort + '.ssb'

return, ph_E
; return, xas_xrf_stack

end
