improve alg and tests