#! /bin/sh

#
# lqsort -- Copyright 1995 Liam R. E. Quin.  All Rights Reserved.
# This code is NOT in the public domain.
# See the file ../COPYRIGHT for full details.
#
# $Id: lqsort.sh,v 1.2 96/05/15 23:22:37 lee Exp $
#

PROGNAME=`basename $0`
if test x"$CMDNAME" = x""
then
    CMDNAME="$PROGNAME"
else
    CMDNAME="$CMDNAME: $PROGNAME"
fi
export CMDNAME

resultsFormat='${NumberOfWordsInPhrase} ${BlockInFile} ${WordInBlock} ${FID} ${FileName}${NL}'
lqkwicoptions=
mformat=''
SEP=''
sortoptions=

while test $# -gt 0
do
    case "$1" in
    -[dfinru])
	sortoptions="$sortoptions $1"
	;;
    -lqkwic)
	lqkwicoptions="${lqkwicoptions} $2"
	shift;
	;;
    "-key")
	if test -z "${mformat}"
	then
	    mformat="\${$2}"
	else
	    mformat="${mformat}${SEP}\${$2}"
	fi
	shift;
	;;
    -help|-usage|-x|-xv|-xvv)
	echo "$$CMDNAME: sort an lq-text results list" 1>&2
	cat 1>&2 << boy
    Use the option  -key variableName  to say how the output is to
    be sorted.  The variableNames are the same as those listed by
	lqkwic -Lxv
    and are not case sensitive.

    Use ! in front of a variable to reverse its contents for the purpose
    of sorting; use !! to reverse its contents by word; prepend a third
    ! to get the words in the reverse order but spelled forwards;
    you can also append a format with /, for example MatchedText/3.3 to use
    only the first 3 characters of he variable for sorting.

    Note that csh and ksh users will have to use \\! to prevent the
    shell from treating the !-signs as references to the shell history.

    Examples:
    
    To sort the output by document title:
	$PROGNAME -key DocumentTitle
    
    The default (i.e. unsorted):
	$PROGNAME -key FileNumber -key MatchNumber

    To sort by the word to the left of the match, then by the matched
    word, then by the word to the right of the match:
	$PROGNAME -key !!!TextBefore -key MatchedText
    
    Other Options:
	-lqkwic "stuff"
	pass "stuff" on as an argument to lqkwic during the sort.

	-d, -f, -i, -n, -r and -u are passed to sort(1).
boy
	exit 0
	;;
    --)
	shift;
	lqkwicoptions="${lqkwicoptions} '${@+\"$@\"}'"
	break
	;;
    *)
	echo "$CMDNAME: Unknown option: $1; use -xv for usage" 1>&2
	exit 1
	;;
    esac
    shift
done

lqkwic -S '' -s "${mformat}${resultsFormat}" ${lqkwicoptions} |
sort -t"${SEP}" ${sortoptions} | sed -e 's/^.*//'
