Extracted function and cleaned up a bit