Code refactoring

A lot of code was refactored. All blocking functionality moved to
separate re-usable functions.
Removed some debug messages.