More refactoring and modularity.

Use variables, reduce repetition, etc.