Refactoring and some error cleanup