Fix memory leak, now runs in constant space. other improvements