Added comment, optimization, tests and fixes.