Untested code port
Small refactor to have private methods and vars within closure