Refactoring for a faster and more re-usable function