Added better TCP connection management

Several bug fixes.