Tidy code

* Remove some of the nested if -> foreach -> if -> foreach -> if etc.
* Align code for readability.
* Improve documentation.
Merge pull request #1 from GaryJones/master

Tidy code