#!/bin/sh

# This script finds a list of S-PLUS function names given a method for
# searching,a search word, and a "search list".  The methods are:
#	-n search by name
#	-k search by keyword
#	-t search by word in short title and by name
#
# It works by finding summary files in the directories in
# the search list, and searching through the correct field in the
# summary files for the word given.

# sumname is the name of summary file to be maintained under each directory
# in the search list.
sumname=".Help/.Help.find.sum"

# They must supply at least 3 args
#	(a switch, a word, one or more dirs)
if [ $# -lt 3 ]; then
	echo "Usage: $0 <-n | -k | -t> <word> <search list ...>" >&2
	exit 1
fi

# Grok method and word.  Return (with error) if no method and word.
method=$1
shift
case $method in
	-n|-k|-t)
		word=$1; shift
		;;
	*)
		echo "Usage: $0 <-n | -k | -t> <word> <search list ...>" >&2
		exit 1
		;;
esac

# Process each directory given in the search list.
#	(for each directory, make sure we have a summary file and
#	remember the name of the directory for later).
for i in $*
do
	if [ -d $i/.Help ]; then
		if [ -r $i/$sumname ]; then
			sumfiles="$sumfiles $i/$sumname"
		else
			echo "help.find summary file not found, directory: $i" >&2
			echo "(You could run S-PLUS function help.findsum(\"$i\") to create one)" >&2
		fi
	fi
done

# If no summary files, return (with success).
if [ x"$sumfiles" = x"" ]; then
	exit 0
fi

# Figure out what pattern to use for search of summary files.
# The pattern determines what fields will be searched.
# For topic, I'll look for $word in the first two fields.  I do not insist
# that $word must begin a function name.  Case is ignored.
# The keyword search will find all keywords starting with $word so
# you should not have two keywords with same initial sequence.  You
# might ask why I don't use \< and \> to say $word must be complete
# word: these don't work on HP-UX (v 7.0 on HP 9000/800) grep.
case $method in
	-n)
		pat="^$word.*~~~"
		GREP=grep
		;;
	-k)
		pat="~~~.*~~.*[~ ]$word"
		GREP=grep
		;;
	-t)	
		pat="$word.*~~~"
		GREP=grep
		;;
esac

# Search the correct field in the summary files for the word.
# (add /dev/null to make at least two files)
# Sed off the appropriate information: change
#    filename : function~~~short description~~~keyword
# to
#    function <tab> short description
# This sed mainly extracts the short description (in \2), but also must
# match and save (in \2) zero or more '~'s in the function name part
# to match correctly in case(s) like "~~~~Model Formula Objects~~~etc etc etc"
$GREP -i "$pat" /dev/null $sumfiles |
	sed -e "s/^[^:]*://" -e "s/\(~*\)~~~\(.*\)~~~.*/\1	\2/g" |
	help.sort

# Done.
exit 0
