Fixing indentation differences from previous pull request.
Structured the logging code better.
Introducing connected boolean.
Removing the nested while loops with break statements in favour of error and timeout variables and a do-while construct.

Also, cleaning up and commenting.