This is our first pass at refactoring the code. The code is reduced by 11 lines and quality issue are improved.

You may want to for reference

The changes to note are:

That covers some performance and coding quality, but there are still some issues and it's 50 lines while 18 was promised. So let's refactor again.