added tests, some refinement & bug fixes