Refactor and better error handling