added refactored code from Frank