code refactoring and error fix