Separated database code out and did some cleanup.