#!/bin/ksh

LIST=0;

while [ $# -gt 0 ]; do
	if [ "$1" = "-l" ]; then
		LIST=1;
		shift;
	elif [ "$1" = "-L" ]; then
		LIST=2;
		shift;
	else
		break;
	fi
done

if [ ! -r tags ]; then
	ctags *.[ch]
fi

typeset -i LINE_NO N

if [ $LIST -eq 0 ]; then
	EXPR=$(echo "^$1\t")
else
	EXPR=$(echo "^$1.*\t")
fi

export MQC_SEARCH="$1";

egrep "$EXPR" tags |&

if [ $LIST -ne 0 ]; then
	# Produce list of tags matching this
	while read SYMBOL FILE EXTRA <&p; do
		if [ $LIST -eq 1 ]; then
			echo "$SYMBOL \c"
		else
			echo "$SYMBOL[$FILE] \c"
		fi
	done
	echo ""
	exit 0;
fi

IFS=`echo "\t"`

n=0;

while read SYMBOL FILE EXTRA <&p
do
	let n=$n+1;
	
	EXTRA=${EXTRA%%;\"*};
	case $EXTRA in
	[0-9]*)
		pterm med -k^L +$EXTRA $FILE
		;;
	/*/)
		EXTRA=${EXTRA#/*}
		EXTRA=${EXTRA%*/}
		EXTRA=`echo "$EXTRA" | sed -e's/*/\\\*/g' -e's/\[/\\\[/g' -e's/\]/\\\]/g'`
		LINE_NO=`textto -l <$FILE | grep -n "$EXTRA" | ( IFS=":"; read L D; echo $L )`
		[ "$LINE_NO" -eq 0 ] && LINE_NO=1
		pterm med -k^L +$LINE_NO $FILE
		;;
	esac
done

[ $n -eq 0 ] && exit 1	# Nothing found
exit 0

