Further changes to speed up existing algorithm