refactor contents of triple loop into separate method