TWSD: added timeout handling, refactored code.