refactoring/code cleanup and adds some tests