code refactoring plus bug fixes