code refactoring and some bug fixes