Refactored to be a LOT more sane.