Error handling, refactoring and a bug fix