Improved code, based on comments on commit 0a2c86383b4c845eb19c8e8f96973c2fae66ed5b
Applied code review, added 2 new helper functions.