refactored code so that it is much more efficient and easier to understand