Adding a check for database being open
More code cleanup