refactored stack iteration