refactor code to put logic all in same function