; Copyright (c) 1998-2009 A.P. Hitchcock  All rights reserved
;+
;NAME:
;		AX_SORT_NAMES
;
;LAST CHANGED: ----------------------------------- 	07-mar-09
;
; PURPOSE:
;	This function sorta a list of filenames by sequence number
; using filename conventions used in NSLS, ALS-PEEM, ALS-STXM, Sphinx, and Lox
;
; CATEGORY:
;	utility
;
; CALLING SEQUENCE:
;	Result = AX_SORT_NAMES(filename_list, [numbers=numbers])
;
; INPUTS:
; 	filename_list = array of strings
;
; KEYWORDS:
;	NUMBERS - if selected, returns an integer array of file numbers rather than sorted names
;
; OUTPUTS: ordered array
;
; COMMON BLOCKS:  none
;
; MODIFICATION HISTORY:
; (23-may-04 aph) first version; adapted from tif_convert
; (07-mar-09 aph) desensitize to alpha characters in filenames (from addition of 'A' at CLS)
;-

Function ax_sort_names, filename_list, number = number
on_error,2

; print, filename_list

nfiles = n_elements(filename_list)
numbs = intarr(nfiles)
; auto definition of character defining start of file number (not all syntaxes have this)
fc='#'			; used with PEEM
t = ax_name(filename_list(0))
npos=rstrpos(t(1),fc)
if npos EQ -1 then fc = '_'		; used with sdf (STXM)
FOR i = 0, nfiles-1 DO BEGIN
	t = ax_name(filename_list(i))
	npos=rstrpos(t(1),fc)
	if npos EQ -1 then begin
  		numbs(i) = fix(strmid(t(1),strlen(t(1))-3))   ; if no # assume 3 spaces before '.'
	endif else begin
		dot_pos = strpos(t(1),'.')		; from CLS stxm  t(1) = 'a090306033_a000.xim  697.00   5'
		t(1) = strmid(t(1),0,dot_pos)
		numbs(i) = fix(strmid(t(1),npos+2))
	endelse
ENDFOR
filename_list = filename_list(sort(numbs))

;print, 'After sorting ....'
;print
;print, filename_list

if keyword_set(number) then return, numbs $
   else return, filename_list
end
