; Copyright (c) 1998-2021 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	AXB_SAVE
;
;LAST CHANGED: ----------------------------------- 06 Jul 2021
;
;PURPOSE:
;	This function writes an AXIS format image or spectrum to the XDR
; transferrable binary format.These files can be read using AXB_LOAD.
;
;CATEGORY:
;	STAND ALONE: utility
;
;CALLING SEQUENCE:
;	Result = AXB_SAVE(tmp [, NOF=nof, file=file, noLbl = noLbl, silent=silent])
;
;CALLED FROM AXIS:
;	Read->Images->AXIS
;
;INPUTS:
;	TMP - AXIS 1d or 2d structure
;
;KEYWORDS:
;	/NOF - no filter (default filter = '*.axb')
;	NOLBL - if set, do not query for label
;   NO_AXIS - do not replot result if not called from aXis2000
;	FILE - filename to write
;	OVERWRITE - if set, overwrite an existing filename
;	SILENT  flag to control entry to axis log
;
;OUTPUTS:
;	RESULT = filename (a blank string if the user cancels)
;
;COMMON BLOCKS:
;	@AXIS_COM	standard set of common blocks
;
;PROCEDURE:
;	uses the XDR external, machine-independent binary representation.
; Please see the IDL manual (help under 'XDR') for details.
; If the filename is not supplied via the FILE keyword, the
; user is prompted for the filename using the pick file dialog.
; If the filename is supplied, a check for overwriting is made unless
; the global flag, overwrite_all is set to 1
;
;EXAMPLE:
; Create a sample nxn image, write as binary using AXB_SAVE, read using AXB_LOAD
;	n = 100 & t = findgen(n) & d = dist(n)
;	a = {t:'2d', x:t, y:t, xl:'x (um)    E = 288.601 eV     dwell =  0.20 ms', yl:'y', d: d, dl:'test'}
;	t = AXB_SAVE(a)
;	b = AXB_LOAD(file = t)
;	splot2d, b
;
;;MODIFICATION HISTORY:
; (  fall-97 aph) first made
; (14-jun-98 aph) axis_com
; (18-jan-99 aph) keyword to allow silent writes (no file dialog)
; ( 8-jul-99 aph) FREE_LUN not just close
; ( 8-sep-99 aph) update label
; (02-jan-00 aph) AXIS standard documentation
; (09-jan-00 aph) add hourglass for long writes
; (27-feb-00 aph) add groupID to get_text
; (06-may-01 aph) remove groupID call if not running axis
; (04-jun-03 aph) add keyword to force label to current value
; (15-Jan-07 aph) add keyword silent
; (29-dec-07 aph) remove path info from log
; (02-Jan-15 aph) add no_aXis keyword to suppress loading result into aXis2000 buffer
; (26-Mar-16 aph) track down problem with wrong # y values (2d images)
;    			  when data comes from Nexus(HDF)
; (12-Apr-16 aph) remove annoying 'help' on the structure
; (24-apr-16 aph) remove problem of incorrect value of ny by using ax_dtf to force tmp.x (.y, .d) to be float, not double
;                   tmp.x is double  despite being forced to be float in read_nexus
; (25-Apr-16 aph) remove ax_dtf ==> fixed in
; (19-Jul-17 aph) force extension to  axb
; (19-Mar-18 aph) troubleshoot unreadable *.axb files written from output of map generation in stack_process
;                 force tmp.x, tmp.y and tmp.d to be REALS (float) ==> they were doubles.
;				   since the routine sometimes worked, suspect there is a singles extra in some cases which made the
;                 the parsing to get ny incorrect. EXAMPLES: C180303048_000 * ___bad-doubles, axis_pass_test_data
; (25-Mar-19 aph) fix problem of not writing if 'silent' keyword is selected
; (22-May-19 aph) fix error in 25-Mar-19 code !
; (23-May-19 aph) if file exists and file was supplied in call; tell user what that file name is
; (21-Jun-19 aph) changed 'test' to 'tt' as use a pro called 'test' !
; (06-Jul-21 aph) add overwrite keyword (so can use same name silently, for ax_fix_rollover)
;
function axb_save, tmp, file = file, noLbl = noLbl, NOF=nof, no_aXis=no_aXis, overwrite=overwrite, silent=silent
@axis_com
on_error,2

; help, tmp, /struct
			; use as internal switch to define if axis is running
if keyword_set(no_aXis) then axis_on = 0 else aXis_on = 1

if n_tags(tmp) NE 0 THEN BEGIN      ; check that tmp is a structure

; --------- don't ask for file name if keyword overwrite is set
IF keyword_set(file) AND keyword_set(overwrite) then goto, skip_get_filename

; check if requested file exists; if so launch overwrite dialog
	IF keyword_set(file) then begin
		check_flag = 1
		if widget_info(/active) EQ 1 then begin
			if overwrite_all EQ 1 then check_flag = 0
		endif
		if check_flag EQ 1 then begin
			tt = findfile(file)
	  		if tt(0) EQ file then begin
	  			t = ax_name(file)
	  			axis_log, t(1) + '.' + t(2) + ' exists already'
	  			if widget_info(/active) EQ 1 then $
			    	t = file_overwrite(group = axis_ID, val = 1) else $
			    	t = file_overwrite(val = 1)
			    if t EQ 0 then file = pickfile2(/write, fltr='*.axb', $
			                      LFILE = file, title = 'Alternate file name')
			    if t EQ 2 then overwrite_all = 1
			endif
		endif

	ENDIF ELSE BEGIN			; filename was not supplied
		fltr='*.axb'
		if keyword_set(nof) then fltr='*'
		file = pickfile2(/write, filter=fltr, /Lpath, $
		       defpath = WritePath) ;, get_path=WritePath)
		if file EQ '' then return, file
		dln = ' '
		if NOT keyword_set(noLbl) then begin
			if widget_info(/active) EQ 1 then $
			    dln = Get_Text(PROMPT = 'Label', val = tmp.dl, group = axis_ID)  $
			    else dln = Get_Text(PROMPT = 'Label', val = tmp.dl)
			tmp.dl = dln(0)
		endif
; ------- update the aXis200buffer since the label may have been changed
		if widget_info(/active) EQ 1 and axis_on EQ 1 then begin
			Label(CurBuf) = tmp.dl
			HANDLE_value, Data(CurBuf), tmp, /set
			BLbl_upd
			widget_control, /hourglass
		endif
	ENDELSE

skip_get_filename: 	;  OK, OK I know this is bad programming !!

; ----- force extension to .axb
	t=ax_name(file)
	file = t(0)+t(1)+'.axb'

; ----- write the structure in binary format
	openw, iunit, file, /get_lun, /XDR
	writeu, iunit, tmp.t
	writeu, iunit, tmp.dl
	writeu, iunit, tmp.xl
	t = ax_name(file) & file_short = t(1)
	CASE tmp.t OF
	  '1d' : begin
	  		writeu, iunit, n_elements(tmp.x)
	  		writeu, iunit, tmp.x
	  		writeu, iunit, tmp.d
	  		writeu, iunit, tmp.dn
	  		writeu, iunit, tmp.xl
	  		writeu, iunit, tmp.dl
	  		if not keyword_set(silent) then  axis_log, 'wrote axis file: ' + file_short + '.axb'
	  	END
	  '2d' : begin
;	  		help, tmp, /struct
			writeu, iunit, tmp.yl
			writeu, iunit, fix(n_elements(tmp.x))
			writeu, iunit, float(tmp.x)
			writeu, iunit, fix(n_elements(tmp.y))
			writeu, iunit, float(tmp.y)
			writeu, iunit, float(tmp.d)
			writeu, iunit, float(tmp.e)
			writeu, iunit, tmp.xl
			writeu, iunit, tmp.yl
			writeu, iunit, tmp.dl
			if not keyword_set(silent) then  axis_log, 'wrote axis file: ' + file_short  + '.axb'
		END
		else :  print, ' Error on binary file write '
	ENDCASE
	close, iunit & free_lun, iunit
	return, file
ENDIF ELSE print, 'AXB_SAVE: not a structure'
END