private static void buildToc(Node node, StringBuilder tocNcx, AtomicInteger counter, AtomicInteger playOrder, AtomicReference<String> lastHref, Map<String, Integer> playOrders) {
        if (node != null) {
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                if (node.getNodeName().equals("item")) {
                    String text = ((Element) node).getAttribute("text");
                    String href = ((Element) node).getAttribute("ref");
                    if (href == null || href.isEmpty()) {
                        href = lastHref.get();
                    } else {
                        lastHref.set(href);
                    }
                    int order;
                    if (playOrders.containsKey(href)) {
                        order = playOrders.get(href);
                    } else {
                        order = playOrder.getAndIncrement();
                        playOrders.put(href, order);
                    }
                    tocNcx.append("<navPoint id=\"id-").append(counter.get()).append("\" playOrder=\"").append(order).append("\">\n");
                    tocNcx.append("<navLabel><text>").append(text).append("</text></navLabel>\n");
                    counter.incrementAndGet();
                    if (href != null && !href.isEmpty()) {
                        tocNcx.append("<content src=\"OEBPS/" + href + "\"/>\n");
                        lastHref.set(href);
                        buildToc(node.getFirstChild(), tocNcx, counter, playOrder, lastHref, playOrders);
                    } else {
                        tocNcx.append("<content src=\"OEBPS/" + lastHref.get() + "\"/>\n");
                        buildToc(node.getFirstChild(), tocNcx, counter, playOrder, lastHref, playOrders);
                    }
                    tocNcx.append("</navPoint>\n");
                } else {
                    buildToc(node.getFirstChild(), tocNcx, counter, playOrder, lastHref, playOrders);
                }
            }
            buildToc(node.getNextSibling(), tocNcx, counter, playOrder, lastHref, playOrders);
        }
    }