Updated to make much more efficient