converted existing logic into function