refactor and error handling