#781 code refactoring
#781 code refactor and a small bug fix
#781 code refactor