Refactor to be more robust