Reduce duplicated code and document very difficult to parse code.
Not sure I entirely understand the requirements that's trying to fill, but whatever