refactoring - added more error handling