#! /usr/bin/perl

use strict;
use warnings;

# generate a link
sub xlink($)
{
  my ($fun) = @_;

  # not documented (first), or do not exist (last two)
  return "<function>$fun</function>"
  if $fun eq 'PQregisterThreadLock' or
     $fun eq 'PQerrorField' or
     $fun eq 'PQsetResultInstanceData';

  my $lfun = lc $fun;
  return "<xref linkend=\"libpq-fun-$lfun\"/>";
}

my %seen_fundef = ();

sub fundef($)
{
  my ($f) = @_;
  my $fun = $1 if $f =~ />(PQ[_a-zA-Z0-9]+)</;
  # do it only once: PQnfields, PQbinaryTuples and PQfformat have 2 defs
  return $f if exists $seen_fundef{$fun};
  $seen_fundef{$fun} = 1;
  my $lfun = lc $fun;
  $f =~ s/<function>/<function id=\"libpq-fun-$lfun\">/;
  return $f;
}

# process all input in one go
$/ = undef;
my $text = <>;
# definitions
$text =~ s,(<function>PQ[_a-zA-Z0-9]*</function>\s*\.?<indexterm>),fundef($1),seg;
# usage
$text =~ s,<function>(PQ[_a-zA-Z0-9]*)</function>(?!\s*\.?<indexterm>),xlink($1),seg;
print $text;
