Fixed error handling and small refactoring