trying to clean up some ugly nested for loop