Added optimization to greatly reduce running time