I again propose breaking this into a helper function.

Having all of this logic inline in this function seems to limit the modularity of this code. and thus its use is limited to the linear flow of this function alone.