         document.tableOfContents = document.generateTableOfContents()
         var tocInserted = false
         var pageIndex = -1
-        for (var i = 0; i < document.document.count; i++) {
-            let docElement = document.document[i]
+        for docElement in document.documentElements {
             let pageNumber = pageIndex + docElement.pageRange.location
             // if (location == 1 && pageNumber == document.tableOfContentsOnPage) || (location == 0 && pageNumber > document.tableOfContents) {
             if(pageNumber >= document.tableOfContentsOnPage && tocInserted == false) {

            var tableOfContents = Array<TableOfContentsElement>()
            
            var pageIndex = -1
            for (var i = 0; i < document.count; i++) {
                let docNode = document[i]
                pageIndex += docNode.pageRange.location
                
                let (textStyle, label) = docNode.functionCall.getTableOfContentsInfo()

        // Start with a clean slate
        self.pdfWriter = initializePDFWriter(0)
        var pageIndex = -1
        for docElement in document.documentElements {
            // page number is: let pageNumber = pageIndex + docElement.pageRange.location
            docElement.executeFunctionCall(pdfWriter, calculationOnly: true)
            pageIndex += (docElement.pageRange.location + docElement.pageRange.length)
