Refactored the tcp code into functions