code refactoring and better error handling