Fix broken loop causing OutOfMemory exception