refactored code according to Robs comments