Performance improvements

Now runs in constant memory, and with only one pass. It has much better performance now.