Potentially fixed a loop which could turn into an infinite loop. Also found another loop which could go wrong.