refactored to integrate two functions