refactored code to use a queue