Fixed issues with PostgreSQL 9.1 and refactored code a bit.