factored out loops to improve performance