Improve closing databases
Change file iteration logic (fixes #3)