Refactor this code to use a loop instead of this complicated if statement crap