refactored close/wait