optimizations, styling, readability

No functionality was changed, just moved around some whitespace, and optimized where there was too much repetition.