Major rewrite separating out the database functions.