Adding unit tests

Adding unit tests and some minor refactoring