Here’s my working code. It works, but it’s ugly.

[paste your code]

Refactor it. Priorities in this order:

  1. Readability — someone else should understand it in 30 seconds
  2. Maintainability — easy to change later without breaking things
  3. Performance — only if there’s a real bottleneck, not micro-optimizations

Keep the same behavior. If you change any interface or signature, call it out explicitly so I don’t miss it.