Refactor generation of table of contents