Refactor window closing algorithm