Refactor into subroutines to make more extensible