First, see my previous article about PostgreSQL functions at sivers.org/pg.