Removed 3rd loop, much more efficient