this looks overly complex and im not following what it is trying to do.

Where are the unittests for this logic ?