Tidy code

* Remove some of the nested if -> foreach -> if -> foreach -> if etc.
* Align code for readability.
* Improve documentation.

Not fully tested yet.