Modified method to group results, add an if statement to prevent failure