; Copyright (c) 1998-2010 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	AX_SORT_MONO
;
;LAST CHANGED: ----------------------------------- 14-Mar-10
;
;PURPOSE:
;	This function sorts (x,y) data sets in ascending values of x
;   and replaces cases of 2 identical X-values with slightly differing values
;   to force monotonic property required for the INTERPOL function
;
;CATEGORY:
;	STAND ALONE: spectral analysis
;
;CALLING SEQUENCE:
;	AX_SORT_MONO[D]
;
;CALLED FROM AXIS:
;	->{Spectra}->Curve Fit

;INPUTS:
;	D		axis2000 format 1-d structure  (OLD: X, Y-values in a 2-d array)
;
;KEYWORDS:
;	AXIS	if flag is set the input is a structure; otherwise a 2-d array **** NOT ACTIVE ***

;OUTPUTS: returns array with x-values organized monotonically; no change to y-values
;
;COMMON BLOCKS: none
;
;PROCEDURE:
;
;MODIFICATION HISTORY:
; (30-dec-03 aph) first version
; (30-Jan-05 aph) remove 2-d array code
; (12-jun-05 aph) modified equal value correction to avoid generating a non-monotonic file !
; (07-mar-10 aph) sort out 'conflcting data structure tag 'y'
; (14-mar-10 aph) return axis paramater
;-

Function ax_sort_mono, d, axis=axis

; help, d, /struct
;IF keyword_set(axis) THEN BEGIN
	x = d.x
	y = d.d
;ENDIF ELSE BEGIN
;	x = d(0,*)
;	y = d(1,*)
;ENDELSE
; first sort in ascending order
	order = sort(x)
	x = x(order)
	y = y(order)
	test = sort(order)
	if total(abs(order-test)) NE 0 then begin
		print, 'ax_sort_mono: x-axis out of order: sorted'
	endif
; then check if there are any equal values
	nx = n_elements(x)
	delta = 0.01*(x(nx-1) - x(0))/nx
     for i = 0, nx-2 do begin
       	if (x(i+1) EQ x(i)) then begin
       		t = x(i)
     		x(i) = x(i) - delta
     		print, 'ax_sort_mono: non-monotonic data found & corrected at point', i, t, ' changed to ', x(i)
     	endif
     endfor

;IF keyword_set(axis) THEN BEGIN
	d.x = x
	d.d = y
;ENDIF ELSE BEGIN
;	d(0,*) = x
;	d(1,*) = y
;ENDELSE

return, d
end
