toc: Smarter code. Add unit test.