some refactoring, bug fixng