Big refactoring job to clean up code more generally