Added end conditions to loop