utility functions introduced and refactored into function to make the
whole thing more readable.