I'd suggest putting this unit extraction in a separate helper function. This function is already quite long.