fixed some logic, heap exhaustion still occurs