Major database access cleanup, and other bugfixes