fixed a some messy loop code