Refactored for clarity and added docs