; Copyright (c) 1998-2010 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	SPC_SAVE
;
;LAST CHANGED: -----------------------------------  7-Mar-10
;
;PURPOSE:
;	This function saves 1-d (spectra) or 2-d (images) structures in AXIS ascii format.
;
;CATEGORY:
;	STAND ALONE: utility & called from aXis2000 write~axis  and utilities~write image ascii
;
;CALLING SEQUENCE:
;	Result =  SPC_SAVE(S, [file=file, int_factor=int_factor, nolb=nolbl, nof=nof])
;
;CALLED FROM AXIS:
;	Write->AXIS
;
;INPUTS:
;	S - AXIS 1d structure
;
;KEYWORDS:
;	FILE - filename (for silent writes)
;	INT_FACTOR - integer factor used to scale float data to preserve precision still using integer storage (only used for images)
;	SILENT - if set, no traceback
;	NOF - no filter (default filter = '*.txt')
;	NOLBL - if set, do not query for label
;
;OUTPUTS:
;	An ascii file is written to disk
;
;COMMON BLOCKS:
;	@AXIS_COM	standard set of common blocks
;
;MODIFICATION HISTORY:
; ( 7-mar-98 aph) save new label in axis
; (14-JUN-98 aph) axis_com
; (10-jul-98 aph) use *.txt as default name for ascii files
; ( 8-jul-99 aph) FREE_LUN as well as close
; (31-jul-99 aph) conditional use of handle to allow use outside axis
; (08-sep-99 aph) update buffer label
; (28-oct-99 aph) add file keyword for 'silent' writing
; (04-jan-00 aph) proper cancel; AXIs standard documentation
; (27-feb-00 aph) add groupID to get_text
; (11-apr-00 aph) fix error when writing 1d files with small or large values
; (04-jun-03 aph) add keyword to force label to current value
; (19-feb-05 aph) check for non-monotonic data and correct before saving
; (21-mar-05 aph) add int_factor keyword; confirm image write out works
; (14-Feb-06 aph) correct invalid number of points
;         (removed "where", with identification of only non-zero values!)
; (30-apr-07 aph) add space between entires in 2-d write
; (13-apr-08 aph) add check for overwrite; warning and options as for saving image files (axb_save.pro)
; (22-nov-08 aph) remove duplication of overwrite check
; (03-Aug-09 aph) change to shortfile name on axis_log feedback
; (12-dec-09 aph) add silent keyword
; (07-Mar-10 aph) remove keyword axis in call for ax_sort_mono (line 109)
;-

function spc_save, s, file = file, int_factor=int_factor, silent=silent, noLbl = noLbl, NOF=nof
@axis_com
on_error,2

if not keyword_set(file) then begin
	fltr='*.txt'
	if keyword_set(nof) then fltr='*'
	file = pickfile2(/write, FILTER=fltr, /LPATH, DefPath=WritePath) ;, get_path=WritePath)
endif
; ------------- added in 13-Apr-08 BUT it is in pickfile2 if use /write keyword
; ------------- so removed 22-nov-08 (gets rid of a duplication ----------
; check if requested file exists; if so launch overwrite dialog
; print, 'File = ', file
;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
;	test = findfile(file)
;	if test(0) EQ file then begin
;		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='*.txt', title = 'Alternate file name')  ; Lfile = file
;	    if t EQ 2 then overwrite_all = 1
;	endif
;endif

if strlen(file) GT 0 THEN BEGIN  ; bail-out if no filename

; ----- update label unless Nolbl flag is set
	if NOT keyword_set(noLbl) then begin
		if widget_info(/active) EQ 0 then $
		    text = Get_text(PROMPT = 'Label', val = s.dl) $
		    else text = Get_text(PROMPT = 'Label', val = s.dl, group = axis_ID)
		s.dl = text  		; update and save buffer label
		if widget_info(/active) EQ 1 then begin
			Label(CurBuf) = s.dl
			HANDLE_value, Data(CurBuf), s, /set
			BLbl_upd
		endif
	endif
; -- write ascii format data file ---
	openw, iunit, file, /get_lun
	printf, iunit, '% ' + s.t
	printf, iunit, '% ' + s.dl

	CASE s.t OF
	'1d' : BEGIN
; --------- if spectrum, correct non-monotonic (sort, remove equal)----------------
	    s = ax_sort_mono(s)    ;,/axis)
;save 1-D structure {t: d:, x:, xl:, dl:} in 2 column text file
; save 1d data (ascii (x,y) pair with headers)
		np = n_elements(s.x)
		printf, iunit, '% ', strcompress(string(np))
		printf, iunit, '% ' + s.xl
		for i = 0, np-1 do printf, iunit, s.x(i), '  ',s.d(i)
	  END

	'2d' : BEGIN
;save 2-D structure {t: d:, x:, y:, xl:, yl:, dl:}
; in TEXT (ascii) format
      tx = size(s.x)  & ty = size(s.y)
      nx = tx(1)      & ny = ty(1)
      printf, iunit, nx, ny
	  printf, iunit, s.xl
	  form = '('+STRCOMPRESS(STRING(nx)) + '(F) )'
	  printf, iunit, format = form, s.x
	  printf, iunit, s.yl
	  printf, iunit, format = form, s.y
	  printf, iunit, s.dl
	  if keyword_set(int_factor) then begin	  ; option to store as integers
		  fact = 1.0
		  tmp=s.d
		  while  median(tmp) LT 1000 do begin
		  	fact = fact * 10
		  	tmp = fact*tmp
		  	print, 'LT 1000 ', fact
		  endwhile
		  tmp=s.d
		  while median(tmp) GT 10000 do begin
		  	fact = fact / 10.
		  	tmp = fact*tmp
		  	print, 'GT 10000 ', fact
		  endwhile
		  text = 'Writing integers. Data multiplied by ' + string(strtrim(fact,2))
		  axis_log, text
		  printf, iunit, fact,' = multiplicative factor. START OF 2-d IMAGE DATA '
		  form = '('+STRCOMPRESS(STRING(nx)) + '(I) )'
	      for j = 0, ny-1 do printf, iunit, format = form, fix(fact*s.d(*,j))
	    endif else begin
			form = '('+STRCOMPRESS(STRING(nx)) + '(G) )'
	    	for j= 0, ny-1 do begin
	    		jline = s.d(*,j)
	    	    printf, iunit, format = form, jline
	    	endfor
	    endelse
      END
	ENDCASE
	close, iunit & free_lun, iunit
	t=ax_name(file)
	if not keyword_set(silent) then begin
		text = 'wrote data to ASCII file: ' + t(1)
		axis_log, text
	endif
endif else begin 	; go here if user pushes 'cancel'
axis_log, ' File not written. No (or invalid) file name'
endelse
return, file
end