refactor tests and fix bugs