Fix loop termination after if statement