Reworked to be much more efficient and fix nullPointer.