Refactored a bit to prepare for next round of improvements.