#!/bin/ksh

usage()
{ echo 'usage:
  which.elb [ -p dir1:dir2:..dir ] [ -f format ] [ -h ] cmnd_list...
  Switches:
    -p dir1:dir2:..:dirN # Colon separated list of dirs, default is $PATH
    -f 0                 # no output, check only existance of files
       1                 # path_list (default)
       2                 # N path_list
       3                 # N basename --> path_list
    -h                   # print help

  Return codes:
    0 executables found
    1 no executables found
    2 Syntax error etc.

  examples:
    which.elb ls tar rm    # $PATH is default
    which.elb -p $ANY_PATH `ls /usr/local/bin`'
if [ "$1" ] ; then echo; echo $1; fi
exit 2
}

P=${PATH}    # actual path is default
CL=''        # command list
EXIT_CODE=1  # no cmnd found assumed to be an error
FORMAT=1     # default format

while [ $# -gt 0 ]
do
  case $1 in
   -p) shift; P=$1 ;;
   -f) shift; FORMAT=$1 ;;
   -h) usage ;;
    *) CL="${CL} $1" ;; # assuming next parameter is executable
   esac
  if [ $# != 0 ]; then shift; else usage "Missing parameter"; fi
done

for cmnd in `echo ${CL} | tr " " "\012" | sort -u`
do
  N=0
  FL=''
  for d in `echo $P | tr ":" "\012"`  # do not sort PATH
  do
    if [ -x ${d}/${cmnd} ]
    then (( N=${N}+1 )) ; FL="${FL} ${d}/${cmnd}"; EXIT_CODE=0
    fi
  done
  FL=`echo "${FL}" | cut -c 2-` # remove leading blank
  case ${FORMAT} in
   0) ;;
   1) echo "${FL}" ;;
   2) echo "${N} ${FL}" ;;
   3) echo "${N} $cmnd --> ${FL}" ;;
   *) usage "Illegal format ${FORMAT}" ;;
   esac
done

exit ${EXIT_CODE}