Simplified code, made it faster by reducing required checks.