Refactoring code, using stack