#! /bin/sh

dir='/man /usr/man'

usage()
{
  echo "Usage: man [SECTION] FPAGE"
  exit 1
}

not_found()
{
  echo "No manual entry for $1"
  exit 1
}

explicit_section()
{
  test "`echo $1|sed 's/^[0-9]*$/0/'`" = 0 || usage
  any1=false
  for x in $dir
  do
    f="$x/$2.$1"
    if [ -f "$f" ]
    then
      any1=true
      less "$f"
    fi
  done
  $any1
}

auto_section()
{
  any2=false
  for s in 1 5
  do
    explicit_section $s "$1" && any2=true
  done
  $any2
}

if [ $# -eq 1 ]
then
  auto_section "$@" || not_found "$1"
elif [ $# -eq 2 ]  
then
  explicit_section "$@" || not_found "$2"
else
  usage
fi
