Slightly sped up version of the same code