Refactor to multiple functions to condense code