Improve closing logic