David,
Did you still want me to take a stab at this in PL/pgSQL?
-- -Josh Berkus Aglio Database Solutions San Francisco