Made algorithm slightly more effecient.