Fix possible crash on malformed databases, slight cleanup.