Fragmentation and unindentation

Separated code into functional pieces to isolate independent mechanisms.
Modified logic to reduce the level of indentation of overall code.