Adding unit tests which imposed some code refactoring