Refactor legacy redirect code and create helper functions