#!/bin/csh -f

#
# Change log:

# separate length check
set retval = 0
if ( $#argv != 1 ) then
   # bad usage sets error status        29 Dec 2015 [rickr]
   set retval = 1
   goto HELP
endif
if ( "$argv[1]" == "-help") goto HELP

set ref_in = $1
set dataset_path = './'


# if path to dset, test separately    31 Jul 2015 [rickr]
# (differs from ./$ref_in if path is absolute)
set dir = "$ref_in:h"
if ( "$dir" != "$ref_in" ) then
    if ( `@CheckForAfniDset ${ref_in}` == 2 ) then
	echo $dir
        exit 0
    endif
endif


if ( $?AFNI_GLOBAL_SESSION ) then
    set dataset_path = (${dataset_path} `echo $AFNI_GLOBAL_SESSION | tr ':' ' '`)
endif

if ( $?AFNI_ATLAS_PATH ) then
    set dataset_path = (${dataset_path} `echo $AFNI_ATLAS_PATH | tr ':' ' '`)
endif

if ( -d $HOME/.afni/atlases ) then
    set dataset_path = (${dataset_path} $HOME/.afni/atlases)
endif

if ( $?AFNI_PLUGINPATH ) then
    set dataset_path = (${dataset_path} `echo $AFNI_PLUGINPATH | tr ':' ' '`)
endif

foreach dir (${dataset_path})
    if ( `@CheckForAfniDset ${dir}/${ref_in}` == 2 ) then
	echo $dir
	exit 0
    endif
end

# Check afni bin directory, for compatibility with older installations
# that installed atlas datasets there.
set wa = `which afni`
if ( $status != 0) then
   exit 1
endif
set ref_path = "$wa:h"
if ( "$ref_path" == "$wa" ) then
   exit 1
endif
if ( `@CheckForAfniDset ${ref_path}/${ref_in}` ) then
    echo ${ref_path}
    exit 0
endif

# not found
exit 1


HELP:
cat << EOF

Usage: `basename $0` <dsetname>

Search AFNI_GLOBAL_SESSION, AFNI_PLUGINPATH, and afni bin directory
(in that order) for named dataset.  If found, echo the first valid path
discovered and return zero status.  If not found, return non-zero status.

   -help to get this message

Jason W. Bacon
Medical College of Wisconsin
Sep 27, 2006

EOF

# be explicit
exit $retval

