         pdfWriter.openPDF(pdfFilePath, title: pdfTitle, author: authorName)
         pageIndex = -1
         
-        for (var i = 0; i < document.document.count; i++) {
-            let docElement = document.document[i]
+        for docElement in document.documentElements {
             // page number is: let pageNumber = pageIndex + docElement.pageRange.location
             docElement.executeFunctionCall(pdfWriter, calculationOnly: false)
             pageIndex += (docElement.pageRange.location + docElement.pageRange.length)

        let range = pdfWriter.addImages(imagePaths, imageCaptions: imageCaptions, imagesPerRow: imagesPerRow, spacing: spacing, padding: padding, calculationOnly: true)
        let funcCall = DocumentStructure.FunctionCall.addImages(imagePaths: imagePaths, imageCaptions: imageCaptions, imagesPerRow: imagesPerRow, spacing: spacing, padding: padding)
        let docNode = DocumentStructure.DocumentElement(functionCall: funcCall, pageRange: range)
        document.document.append(docNode)
        return range
    }
    

            var tableOfContents = Array<TableOfContentsElement>()
            
            var pageIndex = -1
            for docNode in documentElements {
                pageIndex += docNode.pageRange.location
                
                let (textStyle, label) = docNode.functionCall.getTableOfContentsInfo()
