Code cleanup.
Improved exception handling.
Some bugfixes.