refactored, reduced complexity and standardized some loops