#! /usr/bin/perl

use strict;
use warnings;

# existing ids
my %ids = ();

# process all input in one go
$/ = undef;
my $text = <>;

# add an id to a function definition
sub fundef($$)
{
  my ($fd, $lfun) = @_;
  warn "fundef: $lfun\n";
  $fd =~ s/<function>/<function id=\"libpq-$lfun\">/;
  return $fd;
}

my %todo = ();

# generate a link
sub xlink($)
{
  my ($fun) = @_;
  my $lfun = lc $fun;

  # not documented (first), or do not exist (last two)
  #if $fun eq 'PQregisterThreadLock' or
  #   $fun eq 'PQerrorField' or
  #   $fun eq 'PQsetResultInstanceData';
  if (not exists $ids{$lfun} and
      $text =~ m,(<function>$fun</function>\s*\.?<indexterm>),)
  { 
    warn "todo: $fun ($lfun)\n";
    $todo{$fun} = $lfun;
    $ids{$lfun} = 1;
  }

  return "<xref linkend=\"libpq-$lfun\"/>" if exists $ids{$lfun};

  warn "missing: $fun ($lfun)\n";
  return "<function>$fun</function>";
}

# collect existing link targets
warn "collectig ids...\n";
$ids{$1} = 1 while $text =~ /id="libpq-([_a-z0-9]+)"/sg;

# usage
warn "creating links...\n";
$text =~ s,<function>(PQ[_a-zA-Z0-9]*)</function>(?!\s*\.?<indexterm>),xlink($1),seg;

# definitions
warn "creating missing ids...\n";
for my $fun (sort keys %todo)
{
  my $lfun = $todo{$fun};
  $text =~ s|(<function>$fun</function>\s*\.?<indexterm>)|fundef($1,$lfun)|seg;
}

print $text;
