cleanup some loops, rename some functions