Replace if-elses with loop