This would be simpler with a mutable queue