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


-- Returns a key for the ancestor at the given level.  The root is level
-- one.

declare
  p_tree_key      alias for $1;
  p_level         alias for $2;
  v_level         integer default 0;
  v_pos           integer default 1;
begin

  if tree_level(p_tree_key) < p_level then
    raise exception 'tree_ancestor_key: key is at a level less than %', p_level;
  end if;

  while v_level < p_level loop
    v_level := v_level + 1;
    if substring(p_tree_key, v_pos, 1) = '1' then
      v_pos := v_pos + 32;
    else
      v_pos := v_pos + 8;
    end if;
  end loop;

  return substring(p_tree_key, 1, v_pos - 1);

end;$$ language plpgsql;