Refactored most of this but it's all documented now.