Minor code improvements. 

- Reordered module-level code
- Comments added
- Use modern `except Exception as e` syntax (Python2/3 compatible)