refactoring and some bug fixing