improved implementation and tests