I voted to close this question as off-topic because it has working code and is looking for an way to improve it.
It turns out that the code that works only covers part of their solution and will require code duplication to make it work in whole. Based on the answer to part 1 of this question:
If you have a question about a piece of code that meets all of these criteria:
- You wrote it or you contributed to it
- It currently works as intended
- You're looking for improvements to it (e.g. optimization, refactoring, patterns, security, etc)
It's probably better on Code Review than on Stack Overflow.
Technically I see this question meeting all of the criteria (or at least it would if it was written completely). Is it still off topic?