refactors, tests and fixes