fix bug in error handling and refactoring.