Refactor several longer routines into smaller pieces.
Merge branch 'refactor'