<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/perl -- # -*- Perl -*-
#
# $Id: collateindex.pl,v 1.5 2001/03/16 20:15:52 ndw Exp $

use Getopt::Std;

$usage = "Usage: $0 &lt;opts&gt; file
Where &lt;opts&gt; are:
       -p        Link to points in the document.  The default is to link
                 to the closest containing section.
       -g        Group terms with IndexDiv based on the first letter 
                 of the term (or its sortas attribute).
                 (This probably doesn't handle i10n particularly well)
       -s name   Name the IndexDiv that contains symbols.  The default
                 is 'Symbols'.  Meaningless if -g is not used.
       -t name   Title for the index.
       -P file   Read a preamble from file.  The content of file will
                 be inserted before the &lt;index&gt; tag.
       -i id     The ID for the &lt;index&gt; tag.
       -o file   Output to file. Defaults to stdout.
       -S scope  Scope of the index, must be 'all', 'local', or 'global'.
                 If unspecified, 'all' is assumed.
       -I scope  The implied scope, must be 'all', 'local', or 'global'.
                 IndexTerms which do not specify a scope will have the
                 implied scope.  If unspecified, 'all' is assumed.
       -x        Make a SetIndex.
       -f        Force the output file to be written, even if it appears
                 to have been edited by hand.
       -N        New index (generates an empty index file).
       file      The file containing index data generated by Jade
                 with the DocBook HTML Stylesheet.\n";

die $usage if ! getopts('Dfgi:NpP:s:o:S:I:t:x');

$linkpoints   = $opt_p;
$lettergroups = $opt_g;
$symbolsname  = $opt_s || "Symbols";
$title        = $opt_t;
$preamble     = $opt_P;
$outfile      = $opt_o || '-';
$indexid      = $opt_i;
$scope        = uc($opt_S) || 'ALL';
$impliedscope = uc($opt_I) || 'ALL';
$setindex     = $opt_x;
$forceoutput  = $opt_f;
$newindex     = $opt_N;
$debug        = $opt_D;

$indextag     = $setindex ? 'setindex' : 'index';

if ($newindex) {
    safe_open(*OUT, $outfile);
    if ($indexid) {
	print OUT "&lt;$indextag id='$indexid'&gt;\n\n";
    } else {
	print OUT "&lt;$indextag&gt;\n\n";
    }

    print OUT "&lt;!-- This file was produced by collateindex.pl.         --&gt;\n";
    print OUT "&lt;!-- Remove this comment if you edit this file by hand! --&gt;\n";

    print OUT "&lt;/$indextag&gt;\n";
    exit 0;
}

$dat = shift @ARGV || die $usage;
die "$0: cannot find $dat.\n" if ! -f $dat;

%legal_scopes = ('ALL' =&gt; 1, 'LOCAL' =&gt; 1, 'GLOBAL' =&gt; 1);
if ($scope &amp;&amp; !$legal_scopes{$scope}) {
    die "Invalid scope.\n$usage\n";
}
if ($impliedscope &amp;&amp; !$legal_scopes{$impliedscope}) {
    die "Invalid implied scope.\n$usage\n";
}

@term = ();
%id   = ();

$termcount = 0;

print STDERR "Processing $dat...\n";

# Read the index file, creating an array of objects.  Each object 
# represents and indexterm and has fields for the content of the
# indexterm

open (F, $dat);
while (&lt;F&gt;) {
    chop;
    chop if /\r$/;

    if (/^\/indexterm/i) {
	push (@term, $idx);
	next;
    }

    if (/^indexterm (.*)$/i) {
	$termcount++;
	$idx = {};
	$idx-&gt;{'zone'} = {};
	$idx-&gt;{'href'} = $1;
	$idx-&gt;{'count'} = $termcount;
	$idx-&gt;{'scope'} = $impliedscope;
	next;
    }

    if (/^indexpoint (.*)$/i) {
	$idx-&gt;{'hrefpoint'} = $1;
	next;
    }

    if (/^title (.*)$/i) {
	$idx-&gt;{'title'} = $1;
	next;
    }

    if (/^primary[\[ ](.*)$/i) {
	if (/^primary\[(.*?)\] (.*)$/i) {
	    $idx-&gt;{'psortas'} = &amp;escape($1);
	    $idx-&gt;{'primary'} = &amp;escape($2);
	} else {
	    $idx-&gt;{'psortas'} = &amp;escape($1);
	    $idx-&gt;{'primary'} = &amp;escape($1);
	}
	next;
    }

    if (/^secondary[\[ ](.*)$/i) {
	if (/^secondary\[(.*?)\] (.*)$/i) {
	    $idx-&gt;{'ssortas'} = &amp;escape($1);
	    $idx-&gt;{'secondary'} = &amp;escape($2);
	} else {
	    $idx-&gt;{'ssortas'} = &amp;escape($1);
	    $idx-&gt;{'secondary'} = &amp;escape($1);
	}
	next;
    }

    if (/^tertiary[\[ ](.*)$/i) {
	if (/^tertiary\[(.*?)\] (.*)$/i) {
	    $idx-&gt;{'tsortas'} = &amp;escape($1);
	    $idx-&gt;{'tertiary'} = &amp;escape($2);
	} else {
	    $idx-&gt;{'tsortas'} = &amp;escape($1);
	    $idx-&gt;{'tertiary'} = &amp;escape($1);
	}
	next;
    }

    if (/^see (.*)$/i) {
	$idx-&gt;{'see'} = &amp;escape($1);
	next;
    }

    if (/^seealso (.*)$/i) {
	$idx-&gt;{'seealso'} = &amp;escape($1);
	next;
    }

    if (/^significance (.*)$/i) {
	$idx-&gt;{'significance'} = &amp;escape($1);
	next;
    }

    if (/^class (.*)$/i) {
	$idx-&gt;{'class'} = &amp;escape($1);
	next;
    }

    if (/^scope (.*)$/i) {
	$idx-&gt;{'scope'} = &amp;escape(uc($1));
	next;
    }

    if (/^startref (.*)$/i) {
	$idx-&gt;{'startref'} = $1;
	next;
    }

    if (/^id (.*)$/i) {
	$idx-&gt;{'id'} = $1;
	$id{$1} = $idx;
	next;
    }

    if (/^zone (.*)$/i) {
	my($href) = $1;
	$_ = scalar(&lt;F&gt;);
	chop;
	die "Bad zone: $_\n" if !/^title (.*)$/i;
	$idx-&gt;{'zone'}-&gt;{$href} = $1;
	next;
    }

    die "Unrecognized: $_\n";
}
close (F);

print STDERR "$termcount entries loaded...\n";

# Fixup the startrefs...
# In DocBook, STARTREF is a #CONREF attribute; support this by copying
# all of the fields from the indexterm with the id specified by STARTREF
# to the indexterm that has the STARTREF.
foreach $idx (@term) {
    my($ididx, $field);
    if ($idx-&gt;{'startref'}) {
	$ididx = $id{$idx-&gt;{'startref'}};
	foreach $field ('primary', 'secondary', 'tertiary', 'see', 'seealso',
		        'psortas', 'ssortas', 'tsortas', 'significance',
		        'class', 'scope') {
	    $idx-&gt;{$field} = $ididx-&gt;{$field};
	}
    }
}

# Sort the index terms
@term = sort termsort @term;

# Move all of the non-alphabetic entries to the front of the index.
@term = sortsymbols(@term);

safe_open(*OUT, $outfile);

# Write the index...
if ($indexid) {
    print OUT "&lt;$indextag id='$indexid'&gt;\n\n";
} else {
    print OUT "&lt;$indextag&gt;\n\n";
}

print OUT "&lt;!-- This file was produced by collateindex.pl.         --&gt;\n";
print OUT "&lt;!-- Remove this comment if you edit this file by hand! --&gt;\n";

print OUT "&lt;!-- ULINK is abused here.

      The URL attribute holds the URL that points from the index entry
      back to the appropriate place in the output produced by the HTML
      stylesheet. (It's much easier to calculate this URL in the first
      pass.)

      The Role attribute holds the ID (either real or manufactured) of
      the corresponding INDEXTERM.  This is used by the print backends
      to produce page numbers.

      The entries below are sorted and collated into the correct order.
      Duplicates may be removed in the HTML backend, but in the print
      backends, it is impossible to suppress duplicate pages or coalesce
      sequences of pages into a range.
--&gt;\n\n";

print OUT "&lt;title&gt;$title&lt;/title&gt;\n\n" if $title;

$last = {};     # the last indexterm we processed
$first = 1;     # this is the first one
$group = "";    # we're not in a group yet
$lastout = "";  # we've not put anything out yet

foreach $idx (@term) {
    next if $idx-&gt;{'startref'}; # no way to represent spans...
    next if ($idx-&gt;{'scope'} eq 'LOCAL') &amp;&amp; ($scope eq 'GLOBAL');
    next if ($idx-&gt;{'scope'} eq 'GLOBAL') &amp;&amp; ($scope eq 'LOCAL');
    next if &amp;same($idx, $last); # suppress duplicates

    $termcount--;

    # If primary changes, output a whole new index term, otherwise just
    # output another secondary or tertiary, as appropriate.  We know from
    # sorting that the terms will always be in the right order.
    if (!&amp;tsame($last, $idx, 'primary')) { 
	print "DIFF PRIM\n" if $debug;
	&amp;end_entry() if not $first;

	if ($lettergroups) {
	    # If we're grouping, make the right indexdivs
	    $letter = $idx-&gt;{'psortas'};
	    $letter = $idx-&gt;{'primary'} if !$letter;
	    $letter = uc(substr($letter, 0, 1));
	    
	    # symbols are a special case
	    if (($letter lt 'A') || ($letter gt 'Z')) {
		if (($group eq '')
		    || (($group ge 'A') &amp;&amp; ($group le 'Z'))) {
		    print OUT "&lt;/indexdiv&gt;\n" if !$first;
		    print OUT "&lt;indexdiv&gt;&lt;title&gt;$symbolsname&lt;/title&gt;\n\n";
		    $group = $letter;
		}
	    } elsif (($group eq '') || ($group ne $letter)) {
		print OUT "&lt;/indexdiv&gt;\n" if !$first;
		print OUT "&lt;indexdiv&gt;&lt;title&gt;$letter&lt;/title&gt;\n\n";
		$group = $letter;
	    }
	}

	$first = 0; # there can only be on first ;-)

	print OUT "&lt;indexentry&gt;\n";
	print OUT "  &lt;primaryie&gt;", $idx-&gt;{'primary'};
	$lastout = "primaryie";

 	if ($idx-&gt;{'secondary'}) {
	    print OUT "\n  &lt;/primaryie&gt;\n";
	    print OUT "  &lt;secondaryie&gt;", $idx-&gt;{'secondary'};
	    $lastout = "secondaryie";
	};

	if ($idx-&gt;{'tertiary'}) {
	    print OUT "\n  &lt;/secondaryie&gt;\n";
	    print OUT "  &lt;tertiaryie&gt;", $idx-&gt;{'tertiary'};
	    $lastout = "tertiaryie";
	}
    } elsif (!&amp;tsame($last, $idx, 'secondary')) {
	print "DIFF SEC\n" if $debug;

	print OUT "\n  &lt;/$lastout&gt;\n" if $lastout;

	print OUT "  &lt;secondaryie&gt;", $idx-&gt;{'secondary'};
	$lastout = "secondaryie";
	if ($idx-&gt;{'tertiary'}) {
	    print OUT "\n  &lt;/secondaryie&gt;\n";
	    print OUT "  &lt;tertiaryie&gt;", $idx-&gt;{'tertiary'};
	    $lastout = "tertiaryie";
	}
    } elsif (!&amp;tsame($last, $idx, 'tertiary')) {
	print "DIFF TERT\n" if $debug;

	print OUT "\n  &lt;/$lastout&gt;\n" if $lastout;

	if ($idx-&gt;{'tertiary'}) {
	    print OUT "  &lt;tertiaryie&gt;", $idx-&gt;{'tertiary'};
	    $lastout = "tertiaryie";
	}
    }

    &amp;print_term($idx);
    
    $last = $idx;
}

# Termcount is &gt; 0 iff some entries were skipped.
print STDERR "$termcount entries ignored...\n";

&amp;end_entry();

print OUT "&lt;/indexdiv&gt;\n" if $lettergroups;
print OUT "&lt;/$indextag&gt;\n";

close (OUT);

print STDERR "Done.\n";

sub same {
    my($a) = shift;
    my($b) = shift;

    my($aP) = $a-&gt;{'psortas'} || $a-&gt;{'primary'};   
    my($aS) = $a-&gt;{'ssortas'} || $a-&gt;{'secondary'}; 
    my($aT) = $a-&gt;{'tsortas'} || $a-&gt;{'tertiary'};  
	                                            
    my($bP) = $b-&gt;{'psortas'} || $b-&gt;{'primary'};   
    my($bS) = $b-&gt;{'ssortas'} || $b-&gt;{'secondary'}; 
    my($bT) = $b-&gt;{'tsortas'} || $b-&gt;{'tertiary'};  

    my($same);

    $aP =~ s/^\s*//; $aP =~ s/\s*$//; $aP = uc($aP);
    $aS =~ s/^\s*//; $aS =~ s/\s*$//; $aS = uc($aS);
    $aT =~ s/^\s*//; $aT =~ s/\s*$//; $aT = uc($aT);
    $bP =~ s/^\s*//; $bP =~ s/\s*$//; $bP = uc($bP);
    $bS =~ s/^\s*//; $bS =~ s/\s*$//; $bS = uc($bS);
    $bT =~ s/^\s*//; $bT =~ s/\s*$//; $bT = uc($bT);

#    print "[$aP]=[$bP]\n";
#    print "[$aS]=[$bS]\n";
#    print "[$aT]=[$bT]\n";

    # Two index terms are the same if:
    # 1. the primary, secondary, and tertiary entries are the same
    #    (or have the same SORTAS)
    # AND
    # 2. They occur in the same titled section
    # AND
    # 3. They point to the same place
    #
    # Notes: Scope is used to suppress some entries, but can't be used
    #          for comparing duplicates.
    #        Interpretation of "the same place" depends on whether or
    #          not $linkpoints is true.

    $same = (($aP eq $bP)
	     &amp;&amp; ($aS eq $bS)
	     &amp;&amp; ($aT eq $bT)
	     &amp;&amp; ($a-&gt;{'title'} eq $b-&gt;{'title'})
	     &amp;&amp; ($a-&gt;{'href'} eq $b-&gt;{'href'}));

    # If we're linking to points, they're only the same if they link
    # to exactly the same spot.  (surely this is redundant?)
    $same = $same &amp;&amp; ($a-&gt;{'hrefpoint'} eq $b-&gt;{'hrefpoint'})
	if $linkpoints;

    $same;
}

sub tsame {
    # Unlike same(), tsame only compares a single term
    my($a) = shift;
    my($b) = shift;
    my($term) = shift;
    my($sterm) = substr($term, 0, 1) . "sortas";
    my($A, $B);

    $A = $a-&gt;{$sterm} || $a-&gt;{$term};
    $B = $b-&gt;{$sterm} || $b-&gt;{$term};

    $A =~ s/^\s*//; $A =~ s/\s*$//; $A = uc($A);
    $B =~ s/^\s*//; $B =~ s/\s*$//; $B = uc($B);

    return $A eq $B;
}

sub end_entry {
    # End any open elements...
    print OUT "\n  &lt;/$lastout&gt;\n" if $lastout;
    print OUT "&lt;/indexentry&gt;\n\n";
    $lastout = "";
}

sub print_term {
    # Print out the links for an indexterm.  There can be more than
    # one if the term has a ZONE that points to more than one place.
    # (do we do the right thing in that case?)
    my($idx) = shift;
    my($key, $indent, @hrefs);
    my(%href) = ();
    my(%phref) = ();

    $indent = "    ";

    if ($idx-&gt;{'see'}) {
	# it'd be nice to make this a link...
	if ($lastout) {
	    print OUT "\n  &lt;/$lastout&gt;\n";
	    $lastout = "";
	}
	print OUT $indent, "&lt;seeie&gt;", &amp;escape($idx-&gt;{'see'}), "&lt;/seeie&gt;\n";
	return;
    }

    if ($idx-&gt;{'seealso'}) {
	# it'd be nice to make this a link...
	if ($lastout) {
	    print OUT "\n  &lt;/$lastout&gt;\n";
	    $lastout = "";
	}
	print OUT $indent, "&lt;seealsoie&gt;", &amp;escape($idx-&gt;{'seealso'}), "&lt;/seealsoie&gt;\n";
	return;
    }

    if (keys %{$idx-&gt;{'zone'}}) {
	foreach $key (keys %{$idx-&gt;{'zone'}}) {
	    $href{$key} = $idx-&gt;{'zone'}-&gt;{$key};
	    $phref{$key} = $idx-&gt;{'zone'}-&gt;{$key};
	}
    } else {
	$href{$idx-&gt;{'href'}} = $idx-&gt;{'title'};
	$phref{$idx-&gt;{'href'}} = $idx-&gt;{'hrefpoint'};
    }

    # We can't use &lt;LINK&gt; because we don't know the ID of the term in the
    # original source (and, in fact, it might not have one).
    print OUT ",\n";
    @hrefs = keys %href;
    while (@hrefs) {
	my($linkend) = "";
	my($role) = "";
	$key = shift @hrefs;
	if ($linkpoints) {
	    $linkend = $phref{$key};
	} else {
	    $linkend = $key;
	}

	$role = $phref{$key};
	$role = $1 if $role =~ /\#(.*)$/;

	print OUT $indent;
	print OUT "&lt;ulink url=\"$linkend\" role=\"$role\"&gt;";
	print OUT "&lt;emphasis&gt;" if ($idx-&gt;{'significance'} eq 'PREFERRED');
	print OUT &amp;escape($href{$key});
	print OUT "&lt;/emphasis&gt;" if ($idx-&gt;{'significance'} eq 'PREFERRED');
	print OUT "&lt;/ulink&gt;";
    }
}

sub termsort {
    my($aP) = $a-&gt;{'psortas'} || $a-&gt;{'primary'};   
    my($aS) = $a-&gt;{'ssortas'} || $a-&gt;{'secondary'}; 
    my($aT) = $a-&gt;{'tsortas'} || $a-&gt;{'tertiary'};  
    my($ap) = $a-&gt;{'count'};
	                                            
    my($bP) = $b-&gt;{'psortas'} || $b-&gt;{'primary'};   
    my($bS) = $b-&gt;{'ssortas'} || $b-&gt;{'secondary'}; 
    my($bT) = $b-&gt;{'tsortas'} || $b-&gt;{'tertiary'};  
    my($bp) = $b-&gt;{'count'};

    $aP =~ s/^\s*//; $aP =~ s/\s*$//; $aP = uc($aP);
    $aS =~ s/^\s*//; $aS =~ s/\s*$//; $aS = uc($aS);
    $aT =~ s/^\s*//; $aT =~ s/\s*$//; $aT = uc($aT);
    $bP =~ s/^\s*//; $bP =~ s/\s*$//; $bP = uc($bP);
    $bS =~ s/^\s*//; $bS =~ s/\s*$//; $bS = uc($bS);
    $bT =~ s/^\s*//; $bT =~ s/\s*$//; $bT = uc($bT);

    if ($aP eq $bP) {
	if ($aS eq $bS) {
	    if ($aT eq $bT) {
		# make sure seealso's always sort to the bottom
		return 1 if ($a-&gt;{'seealso'});
		return -1  if ($b-&gt;{'seealso'});
		# if everything else is the same, keep these elements
		# in document order (so the index links are in the right
		# order)
		return $ap &lt;=&gt; $bp;
	    } else {
		return $aT cmp $bT;
	    }
	} else {
	    return $aS cmp $bS;
	}
    } else {
	return $aP cmp $bP;
    }
}

sub sortsymbols {
    my(@term) = @_;
    my(@new) = ();
    my(@sym) = ();
    my($letter);
    my($idx);

    # Move the non-letter things to the front.  Should digits be thier
    # own group?  Maybe...
    foreach $idx (@term) {
	$letter = $idx-&gt;{'psortas'};
	$letter = $idx-&gt;{'primary'} if !$letter;
	$letter = uc(substr($letter, 0, 1));

	if (($letter lt 'A') || ($letter gt 'Z')) {
	    push (@sym, $idx);
	} else {
	    push (@new, $idx);
	}
    }

    return (@sym, @new);
}

sub safe_open {
    local(*OUT) = shift;
    local(*F, $_);

    if (($outfile ne '-') &amp;&amp; (!$forceoutput)) {
	my($handedit) = 1;
	if (open (OUT, $outfile)) {
	    while (&lt;OUT&gt;) {
		if (/&lt;!-- Remove this comment if you edit this file by hand! --&gt;/){
		    $handedit = 0;
		    last;
		}
	    } 
	    close (OUT);
	} else {
	    $handedit = 0;
	}
	
	if ($handedit) {
	    print "\n$outfile appears to have been edited by hand; use -f or\n";
	    print "      change the output file.\n";
	    exit 1;
	}
    }

    open (OUT, "&gt;$outfile") || die "$usage\nCannot write to $outfile.\n";

    if ($preamble) { 
	# Copy the preamble
	if (open(F, $preamble)) {
	    while (&lt;F&gt;) {
		print OUT $_;
	    }
	    close(F);
	} else {
	    warn "$0: cannot open preamble $preamble.\n";
	}
    }
}

sub escape {
    # make sure &amp; and &lt; don't show up in the index
    local $_ = shift;
    s/&amp;/&amp;amp;/sg;
    s/&lt;/&amp;lt;/sg;
    s/&gt;/&amp;gt;/sg; # what the heck

    return $_;
}

</pre></body></html>