Improved performance. Added tests.