Moved functions leave and enter outside of for loop