refactored some places to exit functions fast to avoid nesting