Improvements, bug fixes and refactoring.

* Logging system
* More handling of exceptions
* Improved legibility