#!/bin/bash
# Script to get the table of contents out of Postscript file
# generated by groff from all man pages.

if test $# -ne 1; then
	echo "Usage:" `basename $0` "manfile.ps" 1>&2
	exit 0;
fi

if ! test -f $1; then
	echo "File not found: $1" 1>&2
	exit 1;
fi

grep -A5 "^%%Page:" $1 | tr '\\' '*' | sed "s/*214/fi/" |
awk '/^\/F0 /{printf "%s", $0; next} {print}' |
awk '
BEGIN {
    p=0
    prevname="no";
}
/^%%Page: / {
    p=$2;
}
/\/F0 [0-9.]*\/Times-Roman\@0 SF[]?[0-9.]?/ {
    i=0;
    for (n=3; n <= NF; n++)
    {
	prev="";
	for(x=1; x<=length($n); x++)
	{
	    c=substr($n, x, 1);
	    if (i==0)
	    {
		if (c == "(")
		{
		    i=1;
		    continue;
		}
	    }
	    else if (i==1)
	    {
		if (c == ")")
		{
		    if (prev == "*")
		    {
			name=name ")"
			i=2;
		    }
		    else
			i=0;
		}
	    }
	    if ((i==1) && (c != "*"))
		name=name c;
	    prev=c;
	}
    }
    if (name != prevname)
    {
	print name " 	 " p+1;
	print ".br"
    }
    prevname=name;
    name="";
}'
