Stream-line output.
General cleanup and sanitisation.

Remove duplicate or old code.
Add documentation.
Rename functions and variables for clarity.
Formatting.