more unit test and some refactoring and bugfixing