breaking out deeply nested functions, cleaning up