Unit test, refactoring and cleanup