More elegant implementation but still slow