Some cleanup, improved errorhandling.

Some cleanup, improved errorhandling.