Some code re-factoring and properly re-implementing "minor optimization" commit