Refactored to be split into smaller functions