--
-- tree_next_key/2
--
create or replace function tree_next_key(
  bit varying,
  integer
) returns varbit as $$

declare
  p_parent_key      alias for $1;
  p_child_value     alias for $2;
  v_child_value     integer;
begin
-- Create a new child of the given key with a leaf key number one greater than
-- the child value parameter.  If the child value parameter is null, make the
-- child the first child of the parent.

  if p_child_value is null then
    v_child_value := 0;
  else
    v_child_value := p_child_value + 1;
  end if;

  if p_parent_key is null then
    return int_to_tree_key(v_child_value);
  else
    return p_parent_key || int_to_tree_key(v_child_value);
  end if;

end;$$ language plpgsql;