Refactored some nested functions