modified function to make more efficient