Refactored: re-arranged code blocks