refactored code to be much easier to read