Make more functions for reuse

Move more of the work into function so the code can be better reused.