Adapted script to run on Postgres 8.4 :(