#!/bin/sh
# usage: formatman section1,...,sectionn
# Copyright INRIA
formataman()
{
	echo "    processing $1.man"
	sed -e 's/\\f[IPB]//g' -e 's/\\f(CR//g' -e 's/^\.I //' $1.man |tbl|neqn|nroff -man|sed -e ':join
/^ *\n*$/{N
s/\n\n//
b join
}' >$1.cat
}

format()
{
	while [ $# -gt 0 ]
	do
	file=`echo $1|sed -e 's/\.man$//'`
	newest=`ls -t -1 $file.cat $file.man 2>/dev/null |sed -n -e '1p'`
	if [ "$newest" = "$file.man" ]; then
		formataman $file
	fi
	shift
	done
}

mkwhatis()
{
for filename in $*
do
	Base=`basename $filename .man`
        sed -n -e '/^.SH *NAME */,/^.SH */p' $filename | sed -n -e '/ - /p'  |awk '{printf "%s ",$1;i=1;while (i++<=NF) printf "%s ",tolower($i);printf "\n" }' |  sed -e "s/$/ @$Base/" 
done  |\
sed	-e 's/\\(em/-/'		\
	-e 's/\\(hy/-/'		\
	-e 's/\\(mi/-/'		\
	-e 's/ \\- / @/'        \
	-e 's/\\- /@/'		\
	-e 's/  *- / @/'	\
	-e 's/- /@/'		\
	-e 's/ VAX-11//'	\
	-e 's/\.[iI]X *"[^"]*" *"[^"]*" *"[^"]*" *"[^"]*" *//g' \
	-e 's/\.[iI]X *"[^"]*" *"[^"]*" *"[^"]*" *//g'          \
	-e 's/\.[iI]X *"[^"]*" *"[^"]*" *//g'                   \
	-e 's/\.[iI]X *"[^"]*" *//g'                            \
	-e 's/\.cS .*\.cE//'    \
	-e 's/\.PP *//g'	\
	-e 's/\.B *//g'		\
	-e 's/\.rS *//g'	\
	-e 's/\.gL *".*"//g'	\
	-e 's/\.br *//g'	\
	-e 's/\.nL *//g'        \
	-e 's/\\&//g'		\
	-e 's/"" *//g'		\
	-e 's/\.UC [0-9]//g'	\
	-e 's/"\([0-9]*\)"/\1/g' \
	-e 's/"LOCAL"/LOCAL/g'	\
	-e 's/"//g'		\
	-e 's/	\\f[PRIB0123] */	/g' \
	-e 's/\\f[PRIB0123]//g'	\
	-e 's/\\s[-+0-9]*//g'	\
	-e 's/\\\*[LO]//g'	\
	-e 's/\\\//\//g'	\
	-e 's/.TH *[^ ][^ ]* \([^ 	]*\).*	\([^@]*\)@/\2(\1)	- /' \
	-e 's/@/- /'		\
	-e 's/	 /	/g'     \
	-e 's/^ *//' |\
  sort -u >whatis
}

for section in $*
do
  echo formatting section: $section ...
  cd $section

  allfiles=`ls -1 *.man | awk '{print " " $1 }'` 
  format $allfiles
  newest=`ls -t -1 whatis *.cat $file.man 2>/dev/null |sed -n -e '1p'`

  if [ "$newest" != "whatis" ]; then
	echo "    generating: $section/whatis table"
        mkwhatis $allfiles
  fi	
  cd ..
done
exit 0
