refactors function to eliminate branching