Heavy Refactoring and PEP8 Compliance

This patch aims to improve the documentation and readability of the
script. It moves everything from the global namespace into modular and
independent functions which are all orchestrated by the `main` function.

Function and variable names have been made PEP8-compliant and common
Python idioms are used.