Refactor. Add proper logging and error handling