# Written from scratch by Tom Tromey (tromey@cns.caltech.edu)
#
# manpage -- find and print a manual page.
# usage: manpage section name [printing]
#
function manpage ()
{
  local i h cmd zot sec
  local num="$1"
  local page="$2"
  local printing="$3"
  local mp

  mp="${MANPATH:-/usr/man}"
  if [ "$#" -lt 2 ]; then return 1; fi # should print usage
  if [ "$num" != "" ]; then
     sec="${num%%[a-zA-Z]*}"
  else
     sec='[168234571lnpo]'
     num="$sec"
  fi
  for i in $(echo "$mp" | tr : ' '); do
    if [ ! -d "$i" ]; then continue; fi
    file="$i"/man"$sec"/"$page"."$num"*
    set $file
    file="$1"
    if [ -f "$file" ]; then
      zot=$(sed 1q "$file")
      cmd=${MANROFF:-"nroff -man - | col | cat -s"}
      h=${zot##"'"'\"'}
      if [ "$h" != "$zot" ]; then
        while [ "$h" != "" ]; do
          case "$h" in
            *e) cmd="${MANEQN:-neqn} | $cmd";;
            *r) cmd="refer | $cmd";;
            *t) cmd="tbl | $cmd";;
            *v) cmd="vgrind | $cmd";;
            *) ;; # should print error
          esac
          h=${h%?}
        done
      fi
      if [ "$printing" != "" ]; then
        (cd "$i"; eval "$cmd") < "$file" | ${PAGER:-more}
      else
        (cd "$i"; eval "$cmd") < "$file" > /tmp/manpage-$$
        ${PAGER:-more} /tmp/manpage-$$
        rm -f /tmp/manpage-$$
      fi
      break
    fi
  done
}

function whatis_internal ()
{
  local j
  for j in $(echo "$MANPATH" | tr : ' '); do
    if [ -f "$j/whatis" ]; then
      eval $2 -i -e "$1" $j/whatis
    fi
  done
}

function whatis ()
{
  local name=$(basename "$1")
  whatis_internal "$name" "grep -w"
}

function apropos ()
{
  whatis_internal "$1" "grep -F"
}

# Note: "-" and "-t" together not supported.  This man could be
# made a lot better, but it does everything I want.
function man ()
{
  local PAGER printing mpath MANROFF num
  mpath="${MANPATH:-/usr/man}"
  while true; do
    case "$1" in
      -) PAGER=cat
         printing= ;;
      -t)
         MANROFF=${TROFF:-"ptroff -man -t"}
         PAGER="${TCAT:-lpr}"
         printing=yes ;;
      -M)
         mpath="$2"
         shift;;
      *) break;;
    esac
    shift
  done
  local MANPATH="$mpath"
  case "$1" in
    -f | -k)
      local g a
      if [ "$1" = "-f" ]; then
        g="grep -w"
	a=$(basename "$2")
      else
	g="grep -F"
	a="$2"
      fi
      whatis_internal "$a" "$g"
      ;;
    [0-9npol] | [0-9][a-z]* | new | public | old | local)
      if [ "$1" = "new" ]; then
        num=n
      elif [ "$1" = "public" ]; then
        num=p
      elif [ "$1" = "old" ]; then
        num=o
      elif [ "$1" = "local" ]; then
        num=l
      else
	num="$1"
      fi
      shift
      manpage "$num" "$1" "$printing"
      ;;
    *)
      manpage "$num" "$1" "$printing"
      ;;
  esac
}
