Refactoring. Error handling added.