Refactored the code for #3154