factor out loop