Fixed bad loop logic