Factor out a lot of code to reusable functions