Refactor code to resolve #2227 and #2188