; Copyright (c) 1998-2006 A.P. Hitchcock  All rights reserved
;+
;NAME:
;		STACK_READLIST
;
;LAST CHANGED: ----------------------------------- 	21-Feb-06
;
; PURPOSE:
;	This procedure reads in a stack
; set of files from a pre-made list (*.sl) or a listing of files of a specific type
;
; CATEGORY:
;	utility
;
; CALLING SEQUENCE:
;	STACK_READLIST, list_filename, filename_list
;
; INPUTS:
; list_filename	input list
; filename_list	output list
;
; KEYWORDS:  NONE
;
; OUTPUTS:
;filename_list
;
; COMMON BLOCKS: NONE
;
; MODIFICATION HISTORY:
; (10-aug-99 aph) revised to read either zimba or jacobsen format "*.sl" files
; (16-oct-99 aph) set up to handle *sl files with incorrect path information
; (21-feb-06 aph) AXIS standard header added
;-

PRO stack_readlist, list_filename, filename_list

have_a_list = 1
if (n_elements(list_filename) eq 0) then begin
    have_a_list = 0
endif else begin
    it = findfile(list_filename)
    svec = size(it)
    IF (svec(0) eq 0) THEN BEGIN
        have_a_list = 0
    ENDIF
ENDELSE

IF (have_a_list eq 0) THEN BEGIN
    ; We don't have a list, so build it
    stack_buildlist, list_filename, filename_list
ENDIF ELSE BEGIN

;--------------- We have a list
    on_ioerror,bailout
    got_started = 0
    keep_going = 1
    get_lun,lun
    openr,lun,list_filename
    sl_path = ''
	readf, lun, sl_path		; check if first line is only a path
	t = ax_name(sl_path)
	if strlen(t(1)) EQ 0 or  strlen(t(2)) EQ 0 then begin
	   while (keep_going eq 1) do begin
	        this_filename = ''
	        readf,lun,this_filename
	        if (got_started eq 0) then begin
	; ------ OK the first line is a path .... but is it the right one ? !!!!
				file1 = sl_path + this_filename
				check = findfile(file1)
				if strlen(check(0)) EQ 0 then begin
					print, 'Path in ', list_filename,' is incorrect. Finding correct file locations ...'
					sl_path= get_path(file1)
				endif
	            filename_list = [sl_path + this_filename]

	            got_started = 1
	        endif else begin
	            filename_list = [filename_list,sl_path + this_filename]
	        endelse
    	endwhile

	endif else begin
	  close,lun  &  free_lun,lun
 	  get_lun,lun
 	  openr,lun,list_filename
; --------- Jacobsen format SL files -----------
	    while (keep_going eq 1) do begin
	        this_filename = ''
	        readf,lun,this_filename
	        if (got_started eq 0) then begin
	            filename_list = [this_filename]
	            got_started = 1
	        endif else begin
	            filename_list = [filename_list,this_filename]
	        endelse
	    endwhile
	endelse

    bailout:
    close,lun
    free_lun,lun
ENDELSE

return
END
