Minor refactoring and optimizations

Move repeated code into common function