one more loop replaced by algorithm