Improved error handling
Some code refactorings