split the giant encoder loop into two new helper functions.