	; Copyright (c) 1998-2010 A.P. Hitchcock  All rights reserved
;+
;NAME: STACK2_WB
;
;LAST CHANGED: ----------------------------------- 21-Apr-10
;
; PURPOSE:
; This procedure writes  a stack-of-stacks  - I(x,y,SRF-E,a,b)
; where a = fluorescence X-ray energy, b = additional control (e.g. incident photon energy)
;
; CATEGORY:
;	stack-of-stack processing; stand alone operation
;
; CALLING SEQUENCE:
;	WRITE2_WB, FILE, PH_E
;
; INPUTS:
; 	FILE	name of the output file
;	ph_E	array of 4th-dimension parameters (incident photon energies)
;
; KEYWORDS:
;
; OUTPUTS:
;	*.ncb file
;
; COMMON BLOCKS:
; AXIS_COM	standard set of common blocks
; STACK_PROCESS_COM
; BSIF_COM
; volume_data, image_stack
; volume_data2, xas_xrf_stack
;
; PROCEDURE
; 4d array is written to a binary file with associated *.dat file to track paramaters
; data is transferred via Common volume2_data, xas_xrf_stack

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

PRO STACK2_WB, file, ph_E
@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

; --------- write data (integer !)
ax_wait
openw, iunit, file, /get_lun
writeu, iunit, xas_xrf_stack
close, iunit

; ------  write header file
scale = 1.0
t = ax_name(file)
fileshort = t(1)
E_file = t(0)+t(1)+'.dat'
openw, iunit, E_file, /get_lun

im_size = size(xas_xrf_stack)
printf,iunit, im_size(1), im_size(2), im_size(3), scale
n_stacks = im_size(4)

if x_start NE 0 then begin
	x_stop = x_stop - x_start
	x_start = 0.
	y_stop = y_stop - y_start
	y_start = 0.
endif
printf, iunit, x_start, x_stop
printf, iunit, y_start, y_stop

; store X-ray fluorescence energies (same for each stack)
printf, iunit, 'X-ray fluorescence spectral energies (or channels)'
printf, iunit, ev

; store 4th-axis values (e.g. incident photon energies)
printf, iunit, 'Control variable values (e.g. incident photon energies)'
printf, iunit, n_stacks
for i = 0, n_stacks-1 DO printf, iunit, ph_E(i)

; store labels of each stack
printf, iunit, 'Labels '
for i = 0, n_stacks-1 DO begin
	t = ax_name(filename_list(i))
    printf, iunit, t(1), ' ', strtrim(string(ph_E(i), format='(F7.2)'),2)
endfor
close, iunit
free_lun, iunit

ax_wait, /off

;if not keyword_set( silent) then $
axis_log, ' Binary 4-d file (STACK of STACKS) wrote to  ' + fileshort

end
