; Copyright (c) 1998-2011 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	AX_MAKE_XYZ
;
;LAST CHANGED: ----------------------------------- 16-Mar-11 (aph)
;
;PURPOSE:
;	This function reads in an AXIS stack and writes it as a
; set of (x,y,z) triplet data which can be imported
; into various 3D visualization programs (SigmaPlot, Origin )
;
;CATEGORY:
;	STAND ALONE: utility
;
;CALLING SEQUENCE:
;	Result = AXB_make_XYZ([ NOF=nof, error=err, file=file, _extra=e])
;
;CALLED FROM AXIS:
;	STAND ALONE:
;
;INPUTS: none. All input parameters are passed as keywords.
;
;KEYWORDS:
;	FILE	file name
;	SILENT - do not display feedback on progress
;	_EXTRA 	- passed on parameters
;
;OUTPUTS:
;	RESULT = AXIS 1d or 2d structure
;
;COMMON BLOCKS:
;	@AXIS_COM	standard set of common blocks
;   @bsif_com   common for NSLS NetCDF format
;   @stack_process_com
;   volume_data  stack data
;
;
;MODIFICATION HISTORY:

; (15-Mar-11 aph) first version
;-

Function AX_MAKE_XYZ, NOF=nof, file=file, silent=silent, _extra=e
@axis_com
@bsif_com
@stack_process_com

COMMON volume_data, image_stack
on_error,2

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

; -- get stack data
STACK_RB, file

; ---  temporary stack manipulation
 ;image_stack = alog10(image_stack)
 ;file_xyz = pickfile2(/WRITE, title = 'Output file for exp(stack)', FILTER='*.ncb', /LPATH, DEFPATH=defpath)
 ;STACK_WB, file_xyz
 ;return, s

; -- determine if want to reverse z-axis
t=dialog_message('Reverse z-axis values ?',/question)
if t EQ 'Yes' then ev = reverse(ev)

t = size(image_stack)
ncols = t(1)
nrows = t(2)
xstep = (x_stop - x_start)/ncols
x = x_start + findgen(ncols)*xstep
ystep = (y_stop - y_start)/nrows
y = y_start + findgen(nrows)*ystep


; ---- open ascii file for (x,y,z) triplet data
file_xyz = pickfile2(/WRITE, title = 'Text output file for (X,Y,X) tripet data', FILTER='*.txt', /LPATH, DEFPATH=defpath)
openw, iunit, file_xyz, /get_lun
printf,iunit, '%stack file ', file, ' converted to (xyz) triplets'
printf,iunit, '%image size ', ncols, ' * ', nrows
printf,iunit, '%number of energy (control) values) ', n_elements(ev)

; -------- write the triplets
ax_wait
for k = 0, n_elements(ev)-1 do begin
	for i=0, ncols-1 do begin
		for j = 0, nrows-1 do begin
			printf, iunit, x(i), y(j), ev(k), image_stack(i,j,k)
		endfor
	endfor
endfor
ax_wait, /off
close, iunit
free_lun, iunit

return, s
end