refactor, bug fixes, tests