clean-up, refactoring, added tests and fixed resulting bugs