fix loop logic