Speed up algorithm slightly