Revert "Revert "some code refactoring""

This reverts commit c1bd0bcd55d20f86f47f8f98b16b9694c45fbf84.