refactored internals for readability