Refactored somewhat