#! /usr/bin/gawk -f
# /u/sy/beebe/tex/auedindx/authidx.awk, Sun Sep 29 10:07:10 1996
# Edit by Nelson H. F. Beebe <beebe@plot79.math.utah.edu>
### ====================================================================
###  @Awk-file{
###     author          = "Nelson H. F. Beebe",
###     version         = "1.03",
###     date            = "26 February 2002",
###     time            = "18:32:04 MST",
###     filename        = "authidx.awk",
###     address         = "Center for Scientific Computing
###                        University of Utah
###                        Department of Mathematics, 322 INSCC
###                        155 S 1400 E RM 233
###                        Salt Lake City, UT 84112-0090
###                        USA",
###     telephone       = "+1 801 581 5254",
###     FAX             = "+1 801 585 1640, +1 801 581 4148",
###     URL             = "http://www.math.utah.edu/~beebe",
###     checksum        = "53787 1020 4510 33030",
###     email           = "beebe@math.utah.edu (Internet)",
###     codetable       = "ISO/ASCII",
###     keywords        = "author/editor index, BibTeX, bibliography,
###                        LaTeX",
###     supported       = "yes",
###     docstring       = "Process one or more .aei (author/editor
###                        index) files to produce on stdout an .ida
###                        index file that can either be logically
###                        merged with the original .idx file (for a
###                        combined author/editor and subject index), or
###                        processed independently by an indexing
###                        program, such as makeindex, texidx, or
###                        texindex, to produce a separate author/editor
###                        index.
###
###                        Alternatively, if a BibTeX .bbl formatted
###                        bibliography file is given FOLLOWING the
###                        index files on the command line, then the
###                        output will instead be a new .bbl file with
###                        citation page references inserted at the
###                        end of each bibliography entry.
###
###                        This program assumes that BibTeX files have
###                        a consistent form such as that guaranteed by
###                        bibclean, in order to permit simple pattern
###                        matching for parsing BibTeX entries.
###
###                        Usage:
###                             awk -f authidx.awk [MAXNAME=nnn] \
###                                 [ROTATE=n] \
###                                 [SEE=nnn] \
###                                 *.aei >foo.ida
###                        or
###                             authidx [-v MAXNAME=nnn]\
###                                 [ROTATE=n] \
###                                 [SEE=nnn] \
###                                 *.aei >foo.ida
###                        and
###                             awk -f authidx.awk [MAXNAME=nnn] \
###                                 [ROTATE=n] \
###                                 [SEE=nnn] \
###                                 *.aei foo.bbl >foo.bbl-new
###                        or
###                             authidx [-v MAXNAME=nnn]\
###                                 [ROTATE=n] \
###                                 [SEE=nnn] \
###                                 *.aei foo.bbl >foo.bbl-new
###
###                             For separate indexes:
###                                 makeindex -o foo.ina foo.ida
###                                 makeindex -o foo.ind foo.idx
###
###                             For a combined index:
###                                 makeindex -o foo.ind foo.idx foo.ida
###
###                        The MAXNAME option can be used to limit which
###                        author/editor names are indexed.  MAXNAME=1
###                        indexes only the first of them, MAXNAME=2
###                        indexes the first and second, and so on.  The
###                        default is MAXNAME=infinity, for indexing all
###                        names.
###
###                        A non-zero value of the ROTATE=n option
###                        option requests generation of rotated
###                        multi-part names in the index, so that an
###                        author like
###                            Madrid, Jorge de la
###                        will produce cross-referenced entries for
###                            la Madrid, Jorge de
###                        and
###                            de la Madrid, Jorge.
###                        Since conventions about alphabetizing of
###                        multi-part names depend on language and
###                        culture, and since many scientific and
###                        literary bibliographies are international
###                        in nature, it is a convenience to the
###                        reader to be able to a name under any of
###                        the rotated forms, so the default is
###                        ROTATE=1. To suppress generation of the
###                        rotated index entries, use ROTATE =0.
###
###                        The SEE option can be used to control
###                        cross-references from second, third,
###                        ... author/editor names to the first
###                        author/editor name.  SEE=0 suppresses such
###                        cross-referencing; SEE=2 cross-references
###                        only the second author/editor; SEE=3
###                        cross-references the second and third, and so
###                        on.  The default is SEE=infinity, for
###                        complete cross-referencing.
###
###                        The required .aei index files are produced by
###                        using the LaTeX package authidx.sty and
###                        issuing the command \makeauthoreditorindex.
###                        A separate author/editor index can be
###                        obtained by issuing the command
###                        \printauthoreditorindex, assuming a .ida file
###                        has been created as above.  Otherwise,
###                        \printindex will print the combined index.
###
###                        This program requires `new' (1988) awk or
###                        clones such as GNU gawk.
###
###                        Credit: Functions file_exists() and
###                        find_file() below have been borrowed verbatim
###                        from the author's psposter.awk.
###
###                        The checksum field above contains a CRC-16
###                        checksum as the first value, followed by the
###                        equivalent of the standard UNIX wc (word
###                        count) utility output of lines, words, and
###                        characters.  This is produced by Robert
###                        Solovay's checksum utility.",
###  }
### ====================================================================

BEGIN				{ initialize() }

				# convert all non-blank whitespace to blanks
				# in order to simplify later pattern matching
				{ gsub(/[\t\f\n\r]+/," ") }

				# [16-Dec-1999] fix the distinctly unhelpful
				# line wrapping with percent-newline that
				# BibTeX unfortunately provides: if a label
				# is split this way, then previous versions
				# of authidx would not recognize the label,
				# and the corresponding page number would be
				# lost from the \bibindex{...} list, sigh...
				# [21-Dec-1999] the temp variable is necessary
				# to avoid erroneous results with some versions
				# of gawk
				{
				    temp = $0
				    while (temp ~ "%$") # then need to join lines
				    {
					getline line
					temp = substr(temp,1,length(temp)-1) line
				    }
				    $0 = temp
				}

				# NB: We need to set ISBBLFILE during entire
				# processing of .bbl file, rather than just
				# inside thebibliography environment;
				# otherwise, we lose all @Preamble{...}
				# material.
				{ ISBBLFILE = (FILENAME ~ /[.]bbl/) }

/^\\indexentry/			{ indexentry($0); next }

/^\\bibdata/			{ bibdata($0); next }

/^\\bibindex/			{ next } # delete previous bibindex entries

/^\\bibitem/			{ bibitem($0); next }

/^\\harvarditem/		{ bibitem($0); next } # [05-Jun-1999] for harvard.sty

/^ *$/ && (BIBLABEL != "")	{ end_bibitem(); print $0; next }

/^\\begin{thebibliography}/	{ ISBBLFILE = 1; print $0; next }

/^\\end{thebibliography}/	{ end_bibitem(); print $0; next }

# Ignore all other types of lines, except when inside .bbl file
				{ if (ISBBLFILE) print $0; next }

END				{ if (!ISBBLFILE) print_index() }

#=======================================================================

function bibdata(s, bibpaths,filename,k,n,args)
{
    # Typical line:
    # \bibdata{master,lncs,cacm}
    # In documents with chapter bibliographies, there can be multiple
    # bibdata commands, some of which may name the same bibliographies,
    # so we need to accumulate a list of unique BibTeX file names that
    # we will subsequently search.
    sub(/^\\bibdata{/,"",s)
    sub(/}$/,"",s)
    n = split(s,args,/,/)
    split(ENVIRON["BIBINPUTS"],bibpaths,/:/)
    for (k = 1; k <= n; ++k)
    {
	if (match(args[k],/^([.][.]?)?\//))
	{
	    filename = args[k] # absolute or relative file name
	    # handle (legal) case of "./subdir/basename" -> "./subdir/basename.bib"
	    if ((!file_exists(filename)) && file_exists(filename ".bib"))
		filename = filename ".bib"
	}
	else			# search for file on BIBINPUTS path
	    filename = find_file(bibpaths,args[k] ".bib")
	if (filename == "")
	    warning("cannot find BibTeX file " args[k] ".bib in BIBINPUTS path")
	else if (!(filename in BibTeX_file_used)) # then we have a unique new file
	{
	    BibTeX_file[++BibTeX_file_count] = filename
	    BibTeX_file_used[filename] = 1
	    if (DEBUG) print "DEBUG: BibTeX_file[" BibTeX_file_count "] = [" filename "]" >"/dev/stderr"
	}
    }
}


function bibitem(s, k,x)
{
    print s			# copy first line of \bibitem
    while ((brace_level(s) != 0) && (getline x > 0))
    {
        s = s " " x		# handle multiline \bibitem[...]{...}
	print x			# copy more of \bibitem
    }
    for (k = length(s); (k > 0) && (substr(s,k,1) != "{"); --k)
	;			# scan backward to find bibliography label
    if (substr(s,k,1) != "{")
    {
	warning("cannot find citation label in [" s "]")
	return
    }
    BIBLABEL = substr(s,k+1,length(s)-k-1) # discard braces surrounding label
				# and save it in a global variable
}


function brace_level(s, k,level)
{
    level = 0
    for (k = 1; k <= length(s); ++k)
    {
	if (substr(s,k,1) == "{")
	    level++
	else if (substr(s,k,1) == "}")
	    level--
    }

    return (level)
}


function do_author_editor(filename,line,label, k,n,names,x)
{
    line = trim(line)
    while (line !~ /\",?$/)		# " for balance
    {
	getline x <filename
	x = trim(x)
	line = line " " x
    }

    # reduce line to string value
    line = substr(line,index(line,"\"")+1)
    sub(/\",?$/,"",line)		# " for balance

    gsub(/  +/," ",line)		# collapse multiple spaces to single ones

    # In order to deal with cases like
    #   author = "Daniel Gilly and {The Staff of O'Reilly \& Associates, Inc.}"
    # we cannot use a simple split(line,names," and ") call to do the split,
    # so we provide a private enhanced version.
    n = split_at_brace_level_zero(line,names," and ")
    for (k = 1; k <= n; ++k)
    {
	# ignore empty names and "and others" == "et al."
	if ((names[k] != "others") && (names[k] != ""))
	    do_index_entry(names[k],Page[label],k)
    }
}


function do_BibTeX_file(filename, need_entry,label,line)
{
    if (DEBUG) print "DEBUG: do_BibTeX_file(" filename ")" >"/dev/stderr"
    need_entry = 0
    while ((getline line <filename) > 0) # process BibTeX file
    {
	if (line ~ /^ *@ *[Ss][Tt][Rr][Ii][Nn][Gg]/)
	    continue
	else if (line ~ /^ *@ *[Pp][Rr][Ee][Aa][Mm][Bb][Ll][Ee]/)
	    continue
	else if (line ~ /^ *@ *[Cc][Oo][Mm][Mm][Ee][Nn][Tt]/)
	    continue
	else if (line ~ /^ *@ *[A-Za-z]+[{][^,]*, *$/)
	{				# then have, e.g. "@Article{Schreiner:ICC85,...}"
	    sub(/^[^{]+{/,"",line)	# reduce line to
	    sub(/, *$/,"",line)		# citation label
	    label = line
	    need_entry = (label in Page) # remember that we need this entry
	    continue
	}
	else if (line ~ /^ *}/)		# then reached end of entry
	{
	    if (need_entry)		# then we already indexed this entry
		delete Page[label]	# so we ignore this label in subsequent files
	    need_entry = 0
	}
	if (need_entry && (line ~ /^ *(author|editor) *= *\"/))	# " for balance
	    do_author_editor(filename,line,label)
    }
    close(filename)
}


function do_index_compound_name(name,pagenumber,which, k,n,nw,parts,suffix,temp,words)
{
    # Now split compound family names at hyphens, and index each
    # part, as recommended by Words into Type (3rd ed., 1974).
    #	Atherton-Marks-Spenser, Lord Athol  (main entry)
    #	Marks-Spenser, Lord Athol Atherton- (variant 1)
    #	Spenser, Lord Athol Atherton-Marks- (variant 2)

    n = split_at_brace_level_zero(name,parts,", *")
    if (n == 3)
    {
	# Split off any Jr.-like part into a separate suffix string,
	# and reduce name to a normal two-part type.
	if (junior_like(parts[2])) # then like "Harding, Jr., John Wesley"
	{
	    name = parts[1] ", " parts[3]
	    suffix = ", " parts[2]
	}
	else if (junior_like(parts[3])) # then like "Harding, John Wesley, Jr."
	{
	    name = parts[1] ", " parts[2]
	    suffix = ", " parts[3]
	}
	else			# should not happen, so warn user
	{
	    warning("no Jr.-like part 2 or 3 found in [" name "]")
	    suffix = ""
	}
    }

    n = split_at_brace_level_zero(name,parts," +")
    nw = split_at_brace_level_zero(parts[1],words,"-")
    for (k = 2; k <= nw; ++k)
    {
	temp =  join(words,k,nw,"-") " " \
		join(parts,2,n, " ") " " \
		join(words,1,k-1,"-") "-" suffix
	print_indexentry_see(name,sortkey(temp),temp,pagenumber,which)
    }
}


function do_index_entry(name,pagenumber,which, key,n,parts)
{
    # Personal names can be classified into 3 types,
    # based on the number of brace-level zero commas:
    #	(1) P. D. Q. Bach
    #   (2) Bach, P. D. Q
    #   (3) Bach, Jr., P. D. Q.
    #       Bach, P. D. Q., Jr.
    # More than two brace-level zero commas is probably an error.

    n = split_at_brace_level_zero(name,parts,", *")
    if (n == 1)
	do_index_entry_1(name,pagenumber,which)
    else if (n == 2)
	do_index_entry_2(parts[1],parts[2],pagenumber,which)
    else if (n == 3)
	do_index_entry_3(parts[1],parts[2],parts[3],pagenumber,which)
    else
    {
        key = name
	name = name "??too many commas at brace-level zero??"
	print_indexentry(key,name,pagenumber,which)
    }
}


function do_index_entry_1(name,pagenumber,which, k,key,n,parts,temp)
{
    # Index name with no brace-level-zero commas.
    # Typical values:
    #	Jorge de la Madrid
    #   P. D. Q. Bach
    #   {IBM Corporation}

    n = split_at_brace_level_zero(name,parts," +")
    name = parts[n] ((n > 1) ? "," : "")
    for (k = 1; k < n; ++k)
	name = name " " parts[k]
    key = name

    if (ROTATE)
    {
	do_index_compound_name(name,pagenumber,which)

	# Generate rotated variants for index:
	#	de la Madrid, Jorge (main entry)
	#	la Madrid, Jorge de (variant 1)
	#	Madrid, Jorge de la (variant 2)
	# but skip cases where this would put an initial at the start
	# of the entry.
	#
	# In order to avoid cross-referencing of "Wesley Harding,
	# John" to "Harding, John Wesley", we could restrict this
	# rotation to words beginning with a lower case letter
	# (e.g. de, la, von, van), but this would then miss important
	# names where these words are capitalized.

	for (k = 2; k < n; ++k)
	{
	    if (parts[k] !~ /[.]$/)
	    {
	      temp = join(parts,k,n," ") ", " join(parts,1,k-1," ")
	      print_indexentry_see(name,sortkey(temp),temp,pagenumber,which)
	    }
	}
    }
    print_indexentry(key,name,pagenumber,which)
}


function do_index_entry_2(name1,name2,pagenumber,which, \
	k,key,n,name,parts,temp)
{
    # Index name with one brace-level-zero comma.
    # Typical values:
    #	de la Madrid, Jorge
    #   Bach, P. D. Q.
    #   P. D. Q. Bach, Jr.
    #   John D. Rockefeller, III

    name = name1 ", " name2
    key = name

    if (ROTATE)
    {
	do_index_compound_name(name,pagenumber,which)

	# Generate rotated variants for index:
	#	de la Madrid, Jorge (main entry)
	#	la Madrid, Jorge de (variant 1)
	#	Madrid, Jorge de la (variant 2)
	# but skip cases where this would put an initial at the
	# start of the entry.
	#
	# In order to avoid cross-referencing of "Wesley Harding,
	# John" to "Harding, John Wesley", we could restrict this
	# rotation to words beginning with a lower case letter
	# (e.g. de, la, von, van), but this would then miss important
	# names where these words are capitalized.

	n = split_at_brace_level_zero(name1,parts," ")
	for (k = 2; k <= n; ++k)
	{
	    if (parts[k] !~ /[.]$/)
	    {
		temp = join(parts,k,n," ") ", " name2 " " join(parts,1,k-1," ")
		print_indexentry_see(name,sortkey(temp),temp,pagenumber,which)
	    }
	}

	# Generate rotated variants for index:
	#	Madrid, Jorge de la (main entry)
	#	de la Madrid, Jorge (variant 1)
	#	la Madrid, Jorge de (variant 2)
	# but skip cases where this would put an initial at the
	# start of the entry.

	n = split_at_brace_level_zero(name2,parts," ")
	for (k = 2; k <= n; ++k)
	{
	    if (parts[k] !~ /[.]$/)
	    {
		temp = join(parts,k,n," ") " " name1 ", " join(parts,1,k-1," ")
		print_indexentry_see(name,sortkey(temp),temp,pagenumber,which)
	    }
	}
    }

    print_indexentry(key,name,pagenumber,which)
}


function do_index_entry_3(name1,name2,name3,pagenumber,which, \
	k,key,n,name,parts,temp)
{
    # Index name with two brace-level-zero commas.
    # Typical values:
    #	de la Madrid, II, Jorge
    #   Bach, Jr., P. D. Q.
    #   Bach, P. D. Q., Jr.
    #   Rockefeller, III, John D.
    #   Rockefeller, John D., III
    #
    # The Chicago Manual of Style (14th ed., 1993), and the MLA
    # Handbook for Writers of Research Papers (4th ed., 1995) require
    # Jr.-like suffixes to be at the end of an inverted list (Bach,
    # P. D. Q., Jr. instead of Bach, Jr., P. D. Q.), though I
    # personally feel that this has questionable logic.
    #
    # Words into Type (3rd ed., 1974) further recommends that English
    # compound names be indexed under both parts:
    #	Campbell-Bannerman, Sir Henry
    #	Bannerman, Sir Henry Campbell-

    name = name1 ", " name2 ", " name3
    key = name

    if (ROTATE)
    {
	do_index_compound_name(name,pagenumber,which)

	# Generate rotated variants for index:
	#	de la Madrid, II, Jorge (main entry)
	#	la Madrid, II, Jorge de (variant 1)
	#	Madrid, II, Jorge de la (variant 2)
	# but skip cases where this would put an initial at the
	# start of the entry.
     	n = split_at_brace_level_zero(name1,parts," +")
	for (k = 2; k <= n; ++k)
	{
	    if (parts[k] !~ /[.]$/)
	    {
		temp = join(parts,k,n," ") ", " name2 ", " name3 \
		    " " join(parts,1,k-1," ")
		print_indexentry_see(name,sortkey(temp),temp,pagenumber,which)
	    }
	}

	# Generate rotated variants for index:
	#	Madrid, Jorge de la, II (main entry)
	#	de la Madrid, Jorge, II (variant 1)
	#	la Madrid, Jorge de, II (variant 2)
	# but skip cases where this would put an initial at the
	# start of the entry.

	n = split_at_brace_level_zero(name2,parts," ")
	for (k = 2; k <= n; ++k)
	{
	    if (parts[k] !~ /[.]$/)
	    {
		temp = join(parts,k,n," ") " " name1 ", " \
		    join(parts,1,k-1," ") ", " \
		    name3
		print_indexentry_see(name,sortkey(temp),temp,pagenumber,which)
	    }
	}

	# Generate rotated variants for index:
	#	Madrid, II, Jorge de la (main entry)
	#	de la Madrid, II, Jorge (variant 1)
	#	la Madrid, II, Jorge de (variant 2)
	# but skip cases where this would put an initial at the
	# start of the entry.

	n = split_at_brace_level_zero(name3,parts," ")
	for (k = 2; k <= n; ++k)
	{
	    if (parts[k] !~ /[.]$/)
	    {
		temp = join(parts,k,n," ") " " name1 ", " \
		    name2 ", " join(parts,1,k-1," ")
		print_indexentry_see(name,sortkey(temp),temp,pagenumber,which)
	    }
	}
    }

    print_indexentry(key,name,pagenumber,which)
}


function end_bibitem()
{
    if (BIBLABEL != "")
    {
	print "\\bibindex{" fix_pagenumbers(Page[BIBLABEL]) "}"
	BIBLABEL = ""
    }
}


function file_exists(filename)
{
    # Unfortunately, getline in both nawk and gawk will hang if its
    # file does not exist, so we need to test for file existence by
    # invoking a shell command, sigh...

    return (system("test -f " filename) == 0)
}


function find_file(path,filename, fullname,k)
{
    for (k = 1; k in path; ++k)
    {
	fullname = path[k] "/" filename
	if (file_exists(fullname))
	    return (fullname)
    }
    return ("")
}


function fix_junior(name, k,n,parts)
{
    # The Chicago Manual of Style (14th ed., 1993), and the MLA
    # Handbook for Writers of Research Papers (4th ed., 1995) require
    # Jr.-like suffixes to be at the end of an inverted list (Bach,
    # P. D. Q., Jr. instead of Bach, Jr., P. D. Q.), though I
    # personally feel that this has questionable logic.  Nevertheless,
    # let us follow their recommendations to avoid the wrath of book
    # copyeditors.

    n = split_at_brace_level_zero(name,parts,", *")
    for (k = 1; k < n; ++k)
    {
	if (junior_like(parts[k]))
	    return (join(parts,1,k-1,", ") ", " \
		    join(parts,k+1,n,", ") ", " parts[k])
    }
    return (name)
}


function fix_pagenumbers(pagenumbers, range,j,jstart,k,n,parts,temp)
{
    n = split(pagenumbers,parts,",")

    # Sort the page numbers; the list is almost always
    # in order, and short, so this n^2 sort is fast enough.
    for (j = 1; j < n; ++j)
    {
	for (k = j + 1; k <= n; ++k)
	{
	    if (pagevalue(parts[j]) > pagevalue(parts[k]))
	    {
	        temp = parts[j]
		parts[j] = parts[k]
		parts[k] = temp
	    }
	}
    }

    if (DEBUG) print "DEBUG: pagenumbers = [" pagenumbers "]" >"/dev/stderr"

    # Now that we have a sorted list of numbers, possibly with duplicates,
    # create a new list of page numbers with runs of consecutive pages
    # collapsed to page ranges, each covering at least 3 pages.
    parts[n+1] = parts[n]	# boundary value needed in while loop below
    pagenumbers = ""
    for (j = 1; j <= n; ++j)
    {
	if (DEBUG) print "DEBUG: parts[" j "] = [" parts[j] "] == [" pagevalue(parts[j]) "]" >"/dev/stderr"
        jstart = j
	while ((j <= n) && ((pagevalue(parts[j+1]) - pagevalue(parts[j])) <= 1))
	    j++			# advance over page range
	pagenumbers = pagenumbers ((jstart == 1) ? "" : ", ") parts[jstart]
	range = pagevalue(parts[j]) - pagevalue(parts[jstart])
	if (range > 0)
	    pagenumbers = pagenumbers ((range > 1) ? "--" : ", ") parts[j]
    }

    return (pagenumbers)
}


function indexentry(s, k,n,args,labels)
{
    # Typical line:
    # \indexentry{Johnson:yacc,Levine:LY92,Mason:LY90,Schreiner:ICC85}{406}
    sub(/^\\indexentry{/,"",s)
    n = split(s,args,/}{/)
    if (n != 2)
    {
	warning("unrecognized \\indexentry: " $0)
	return
    }
    sub(/}$/,"",args[2])
    n = split(args[1],labels,/,/)
    for (k = 1; k <= n; ++k)
	Page[labels[k]] = ((labels[k] in Page) ? (Page[labels[k]] ",") : "") \
	    args[2]
}


function initialize( infinity)
{
    infinity = 2^14 + (2^14 - 1) # largest signed 16-bit integer

    ISBBLFILE = 0

    if ((MAXNAME == "infinity") || (MAXNAME == ""))
	MAXNAME = infinity
    MAXNAME += 0		# force to numeric value

    if ((ROTATE == "infinity") || (ROTATE == ""))
	ROTATE = infinity
    ROTATE += 0			# force to numeric value

    if ((SEE == "infinity") || (SEE == ""))
	SEE = infinity
    SEE += 0			# force to numeric value

    BibTeX_file_count = 0
}


function item_count(array, count,item)
{
    count = 0
    for (item in array)
	count++
    return (count)
}


function join(array,start,end,separator, k,s)
{
    # Return a string that is a concatenation of
    # array[start] separator array[start+1] separator ... array[end]

    s = array[start]
    for (k = start+1; k <= end; ++k)
        s = s separator array[k]

    return (s)
}


function junior_like(name)
{
    # Return 1 if name is Jr.-like: match against Jr, Sr., Fr., Esq.,
    # upper-case Roman numerals from 2 to 49, and 2-or-more-part
    # University degrees (M.Sc., D.Phil., M.F.A, ...)

    return (name ~ /^([JSF]r[.]?|Esq[.]?|II|III|IV|V|VI|VII|VIII|IX|X|X+I+|X+IV|X+VI*|X+IX|[A-Z][a-z]*[.]([A-Z][a-z]*[.])+)$/)
}


function pagevalue(pagenumber)
{
    # TO DO: Generalize this to handle composite page numbers like
    # makeindex does.

    if (pagenumber ~ /^[ivxlcdm]+$/) # lower-case roman
	pagenumber = -1000000 + romtol(pagenumber)
    else if (pagenumber ~ /^[0-9]+$/) # arabic
	pagenumber = 0 + pagenumber
    else if (pagenumber ~ /^[IVXLCDM]+$/) # upper-case roman
	pagenumber = +1000000 + romtol(pagenumber)

    # Any other format is returned unchanged: this needs to be
    # generalized

    return (pagenumber)
}


function print_index( k,label,n)
{
    # For efficiency, we scan one BibTeX file at a time, outputting
    # index entries for all author/editor names in entries that match
    # any citation label.  We bail out early if all labels have been
    # found, which can happen if the \bibdata{} command supplies a long
    # list of BibTeX files, some of which are not required.

    for (k = 1; (k <= BibTeX_file_count) && (item_count(Page) > 0); ++k)
    {
	if (BibTeX_file[k] != "")
	    do_BibTeX_file(BibTeX_file[k])
    }

    # It is possible that some BibTeX files were not located (e.g. bad
    # BIBINPUTS search path, or misspelled names), so we need to make a
    # sanity check that all cited entries have been indexed.

    n = item_count(Page) # NB: must recompute, since do_BibTeX_file() changes it
    if (n > 0)
    {
	warning("the following " n " citation label" ((n == 1) ? "" : "s") \
	    ((n == 1) ? " was" : " were") " not found")
	for (label in Page)
	    warning("\tmissing: " label)
    }
}


function print_indexentry(key,name,pagenumber,which, k,n,parts,see_index,suffix)
{
    key = fix_junior(key)
    name = fix_junior(name)
    key = sortkey(key)
    suffix = (which == 1) ? "first" : "rest"
    if (which <= MAXNAME)
    {		# output one index entry for each indexed page number
	n = split(pagenumber,parts,",")
	for (k = 1; k <= n; ++k)
	    print "\\indexentry{" key "@\\AEnamefont" suffix "{" name \
	        "}|AEpagefont" suffix "}{" parts[k] "}"
    }

    # NB: We must take care to avoid generating more than one `see' reference
    # for each pair of authors, to avoid makeindex warnings about ``multiple
    # encaps for the same page under same key'', or duplicate see entries.
    if (which == 1)
	FIRSTNAME = name	# global value for subsequent cross-references
    else if (which <= SEE)
    {
	see_index = name SUBSEP FIRSTNAME
	if (!(see_index in See_used))
	{
	    print "\\indexentry{" key "@\\AEnamefont" suffix "{" name \
		"}|see{\\AEnamefontfirst{" FIRSTNAME "}}}{0}"
	    See_Used[see_index] = 1
	}
    }
}


function print_indexentry_see(seename,key,name,pagenumber,which, see_index,suffix)
{
    # NB: We must take care to avoid generating more than one `see' reference
    # for each pair of authors, to avoid makeindex warnings about ``multiple
    # encaps for the same page under same key'', or duplicate see entries.

    suffix = (which == 1) ? "first" : "rest"
    see_index = name SUBSEP seename
    if ((which <= SEE) && !(see_index in See_used))
    {
	print "\\indexentry{" key "@\\AEnamefont" suffix "{" name \
	    "}|see{\\AEnamefontfirst{" seename "}}}{0}"
	See_Used[see_index] = 1
    }
}


function romtol(s, k,last_value,number,value)
{
    # Credit: This code, and its introductory comments, is borrowed
    # from romtol.c in my bibclean 2.11 distribution.
    #
    # Roman numbers are represented with the symbols i (1), v (5), x (10), l
    # (50), c (100), d (500), m (1000), v-overbar (5000), x-overbar (10000),
    # c-overbar (100000), m-overbar (1000000) in a peculiar way.  There is
    # no representation of zero at all, and letter case is NOT significant.
    # `Digits' are ordinarily given in order of descending numerical values,
    # with the number value being the sum of the digit values.  However, if
    # a larger digit follows a smaller one, then the smaller one is
    # subtracted from the larger one.  Thus, ix is -1 + 10 = 9, while xi is
    # 10 + 1 = 11.
    #
    # One source that I consulted claimed that when digits are repeated, the
    # subtraction rule is suppressed, so iiix would be 3 + 10 = 13, not 2 -
    # 1 + 10 = 11.  The current code does not implement this feature; iiix
    # will evaluate to 11.
    #
    # The overbar representation for 5000 and up is not representable in
    # most computer character sets, so we ignore it here.
    #
    # The Roman number representation is not unique.  For example, clocks
    # traditionally use iiii for 4, while iv is used elsewhere.  1990 can be
    # written as mxm or mcmxc.

    s = trim(s)
    last_value = 0
    number = 0
    for (k = 1; k <= length(s); ++k)
    {
	value = roman_digit_value(substr(s,k,1))
	if (value == 0)		# not a roman digit, so quit conversion
	{			# but issue a warning
	    warning("non-roman digit detected in numeral [" s "]")
	    break
	}
	if (value > last_value)
	    number -= last_value
	else
	    number += last_value
	last_value = value
    }
    number += last_value
    return (number)
}


function roman_digit_value(c)
{
    if ((c == "i") || (c == "I"))
	return (1)
    else if ((c == "v") || (c == "V"))
	return (5)
    else if ((c == "x") || (c == "X"))
	return (10)
    else if ((c == "l") || (c == "L"))
	return (50)
    else if ((c == "c") || (c == "C"))
	return (100)
    else if ((c == "d") || (c == "D"))
	return (500)
    else if ((c == "m") || (c == "M"))
	return (1000)
    else
	return (0)		# unrecognized roman digit
}


function sortkey(name)
{
    gsub(/\\ae */,"ae",name)		# Scandinavian letters
    gsub(/\\aa */,"aa",name)
    gsub(/\\AE */,"Ae",name)
    gsub(/\\AA */,"Aa",name)

    gsub(/\\oe */,"oe",name)		# OE/oe ligatures
    gsub(/\\OE */,"Oe",name)

    gsub(/\\ss */,"ss",name)		# es-zet -> ss

    gsub(/\\[A-Za-z][A-Za-z]+ */,"",name) # discard remaining 2-or-more-letter
					# TeX control sequences

    # Both the Chicago Manual of Style (14th ed., 1993), and the MLA
    # Handbook for Writers of Research Papers (4th ed., 1995)
    # recommend ignoring accents for sorting purposes (in American
    # English text).  Danish/Norwegian \o is the same letter as
    # Swedish \"o, so both are collapsed to o, instead of oe.

    gsub(/\\o */,"o",name)		# more Scandinavian letters
    gsub(/\\O */,"O",name)

    gsub(/\\i */,"i",name)		# dotless i -> i
    gsub(/\\j */,"j",name)		# dotless j -> j

    gsub(/\\l */,"l",name)		# Polish l -> l
    gsub(/\\L */,"L",name)		# Polish L -> L

    # NB: we may want to preserve accents, since makeindex 3.xx will be
    # able to handle sorting of accented letters more flexibly.  For
    # now, however, we drop them, since makeindex 2.xx will otherwise
    # just treat them as ordinary characters.
    gsub(/\\[`'^\"~=.uvHtcdbk] */,"",name) # (" for balance)
					# discard accents (Table 3.1,
					# LaTeX Users Guide, 2nd ed, 1994)
					# plus \k (Polish ogonek) accent

    gsub(/\\[A-Za-z]+ */,"",name)	# discard all other TeX control sequences
    gsub(/\\[&]/,"\\&",name)		# \& -> &

    gsub(/[{}]/,"",name)		# discard braces
    gsub(/[$]/,"",name)			# discard math modes (yes, they sometimes occur
					# in badly-written bibliographies)

    return (trim(name))
}


function split_at_brace_level_zero(s,array,regexp, k,level,n)
{
    # Split a string s into array[], but only when regexp occurs
    # at unbackslashed-brace-level 0.

    if (DEBUG) printf("DEBUG: [%s] -> ",s) >"/dev/stderr"

    level = 0
    n = 0
    for (k = 1; k <= length(s); ++k)
    {
	if ((substr(s,k,1) == "{") && (substr(s,k-1,1) != "\\"))
	    level++
	else if ((substr(s,k,1) == "}") && (substr(s,k-1,1) != "\\"))
	    level--
	if (level == 0)			# then we can try for a separator match
	{
	    if (match(substr(s,k),regexp) && (RSTART == 1) && (RLENGTH > 0))
	    {
		array[++n] = substr(s,1,k-1)
		s = substr(s,k - 1 + RSTART + RLENGTH)
		k = 0			# WARNING: restart search
	    }
	}
    }
    array[++n] = s			# last chunk (which might be whole string)

    ## for (k = 1; k <= n; ++k)
    ##     printf("%d:[%s] ",k,array[k])
    if (DEBUG) print "" >"/dev/stderr"

    return (n)
}


function trim(s)
{
    gsub(/^[ \t]+/,"",s)
    gsub(/[ \t]+$/,"",s)
    return (s)
}


function warning(message)
{
#    print FILENAME ":" FNR ":%%" message >"/dev/tty"
    print FILENAME ":" FNR ":%%" message >"/dev/stderr"
}
