Refactor to remove some dead code
Refactor into smaller functions