Reorganized with functions and subroutines at the top; pulled repetitive
elements in ^p into their own subroutine.