This function is getting long and complicated.
Needs to be broken into smaller more reusable pieces.
Instead of adding the 2 new params to the fn signature I suggest creating a new function for those bits.