Refactor and error handling