/* Copyright (C) 2021-2022 Stephan Kreutzer
 *
 * This file is part of xml_to_dimgra_1, a submodule of the
 * digital_publishing_workflow_tools package.
 *
 * xml_to_dimgra_1 is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License version 3 or any later version,
 * as published by the Free Software Foundation.
 *
 * xml_to_dimgra_1 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License 3 for more details.
 *
 * You should have received a copy of the GNU Affero General Public License 3
 * along with xml_to_dimgra_1. If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * @file $/xml_to_dimgra/xml_to_dimgra_1/xml_to_dimgra_1.java
 * @brief Converts selected fields within sections of XML into a multidimensional,
 *     typed graph structure.
 * @author Stephan Kreutzer
 * @since 2021-05-18
 */

import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.util.ResourceBundle;
import java.text.MessageFormat;
import java.io.File;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.HashMap;
import javax.xml.stream.XMLInputFactory;
import java.io.InputStream;
import java.io.FileInputStream;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.events.XMLEvent;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.Attribute;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import java.util.Stack;
import java.util.Iterator;
import java.util.LinkedList;

public class xml_to_dimgra_1
{
    public static void main(String args[])
    {
        System.out.print("xml_to_dimgra_1 Copyright (C) 2021-2022 Stephan Kreutzer\n" +
                         "This program comes with ABSOLUTELY NO WARRANTY.\n" +
                         "This is free software, and you are welcome to redistribute it\n" +
                         "under certain conditions. See the GNU Affero General Public License 3\n" +
                         "or any later version for details. Also, see the source code repository\n" +
                         "https://gitlab.com/publishing-systems/digital_publishing_workflow_tools/ and\n" +
                         "the project website https://publishing-systems.org.\n\n");

        xml_to_dimgra_1 instance = new xml_to_dimgra_1();

        try
        {
            instance.run(args);
        }
        catch (ProgramTerminationException ex)
        {
            instance.handleTermination(ex);
        }

        if (instance.resultInfoFile != null)
        {
            try
            {
                BufferedWriter writer = new BufferedWriter(
                                        new OutputStreamWriter(
                                        new FileOutputStream(instance.resultInfoFile),
                                        "UTF-8"));

                writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
                writer.write("<!-- This file was created by xml_to_dimgra_1, which is free software licensed under the GNU Affero General Public License 3 or any later version (see https://gitlab.com/publishing-systems/digital_publishing_workflow_tools/ and https://publishing-systems.org). -->\n");
                writer.write("<xml-to-dimgra-1-result-information>\n");
                writer.write("  <success>\n");

                if (instance.getInfoMessages().size() > 0)
                {
                    writer.write("    <info-messages>\n");

                    for (int i = 0, max = instance.getInfoMessages().size(); i < max; i++)
                    {
                        InfoMessage infoMessage = instance.getInfoMessages().get(i);

                        writer.write("      <info-message number=\"" + i + "\">\n");
                        writer.write("        <timestamp>" + infoMessage.getTimestamp() + "</timestamp>\n");

                        String infoMessageText = infoMessage.getMessage();
                        String infoMessageId = infoMessage.getId();
                        String infoMessageBundle = infoMessage.getBundle();
                        Object[] infoMessageArguments = infoMessage.getArguments();

                        if (infoMessageBundle != null)
                        {
                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            infoMessageBundle = infoMessageBundle.replaceAll("&", "&amp;");
                            infoMessageBundle = infoMessageBundle.replaceAll("<", "&lt;");
                            infoMessageBundle = infoMessageBundle.replaceAll(">", "&gt;");

                            writer.write("        <id-bundle>" + infoMessageBundle + "</id-bundle>\n");
                        }

                        if (infoMessageId != null)
                        {
                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            infoMessageId = infoMessageId.replaceAll("&", "&amp;");
                            infoMessageId = infoMessageId.replaceAll("<", "&lt;");
                            infoMessageId = infoMessageId.replaceAll(">", "&gt;");

                            writer.write("        <id>" + infoMessageId + "</id>\n");
                        }

                        if (infoMessageText != null)
                        {
                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            infoMessageText = infoMessageText.replaceAll("&", "&amp;");
                            infoMessageText = infoMessageText.replaceAll("<", "&lt;");
                            infoMessageText = infoMessageText.replaceAll(">", "&gt;");

                            writer.write("        <message>" + infoMessageText + "</message>\n");
                        }

                        if (infoMessageArguments != null)
                        {
                            writer.write("        <arguments>\n");

                            int argumentCount = infoMessageArguments.length;

                            for (int j = 0; j < argumentCount; j++)
                            {
                                if (infoMessageArguments[j] == null)
                                {
                                    writer.write("          <argument number=\"" + j + "\">\n");
                                    writer.write("            <class></class>\n");
                                    writer.write("            <value>null</value>\n");
                                    writer.write("          </argument>\n");

                                    continue;
                                }

                                String className = infoMessageArguments[j].getClass().getName();

                                // Ampersand needs to be the first, otherwise it would double-encode
                                // other entities.
                                className = className.replaceAll("&", "&amp;");
                                className = className.replaceAll("<", "&lt;");
                                className = className.replaceAll(">", "&gt;");

                                String value = infoMessageArguments[j].toString();

                                // Ampersand needs to be the first, otherwise it would double-encode
                                // other entities.
                                value = value.replaceAll("&", "&amp;");
                                value = value.replaceAll("<", "&lt;");
                                value = value.replaceAll(">", "&gt;");

                                writer.write("          <argument number=\"" + j + "\">\n");
                                writer.write("            <class>" + className + "</class>\n");
                                writer.write("            <value>" + value + "</value>\n");
                                writer.write("          </argument>\n");
                            }

                            writer.write("        </arguments>\n");
                        }

                        Exception exception = infoMessage.getException();

                        if (exception != null)
                        {
                            writer.write("        <exception>\n");

                            String className = exception.getClass().getName();

                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            className = className.replaceAll("&", "&amp;");
                            className = className.replaceAll("<", "&lt;");
                            className = className.replaceAll(">", "&gt;");

                            writer.write("          <class>" + className + "</class>\n");

                            StringWriter stringWriter = new StringWriter();
                            PrintWriter printWriter = new PrintWriter(stringWriter);
                            exception.printStackTrace(printWriter);
                            String stackTrace = stringWriter.toString();

                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            stackTrace = stackTrace.replaceAll("&", "&amp;");
                            stackTrace = stackTrace.replaceAll("<", "&lt;");
                            stackTrace = stackTrace.replaceAll(">", "&gt;");

                            writer.write("          <stack-trace>" + stackTrace + "</stack-trace>\n");
                            writer.write("        </exception>\n");
                        }

                        writer.write("      </info-message>\n");
                    }

                    writer.write("    </info-messages>\n");
                }

                writer.write("  </success>\n");
                writer.write("</xml-to-dimgra-1-result-information>\n");
                writer.flush();
                writer.close();
            }
            catch (FileNotFoundException ex)
            {
                ex.printStackTrace();
                System.exit(-1);
            }
            catch (UnsupportedEncodingException ex)
            {
                ex.printStackTrace();
                System.exit(-1);
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
                System.exit(-1);
            }
        }
    }

    public int run(String args[])
    {
        if (args.length < 2)
        {
            throw constructTermination("messageArgumentsMissing", null, getI10nString("messageArgumentsMissingUsage") + "\n\txml_to_dimgra_1 " + getI10nString("messageParameterList") + "\n");
        }

        File resultInfoFile = new File(args[1]);

        try
        {
            resultInfoFile = resultInfoFile.getCanonicalFile();
        }
        catch (SecurityException ex)
        {
            throw constructTermination("messageResultInfoFileCantGetCanonicalPath", ex, null, resultInfoFile.getAbsolutePath());
        }
        catch (IOException ex)
        {
            throw constructTermination("messageResultInfoFileCantGetCanonicalPath", ex, null, resultInfoFile.getAbsolutePath());
        }

        if (resultInfoFile.exists() == true)
        {
            if (resultInfoFile.isFile() == true)
            {
                if (resultInfoFile.canWrite() != true)
                {
                    throw constructTermination("messageResultInfoFileIsntWritable", null, null, resultInfoFile.getAbsolutePath());
                }
            }
            else
            {
                throw constructTermination("messageResultInfoPathIsntAFile", null, null, resultInfoFile.getAbsolutePath());
            }
        }

        xml_to_dimgra_1.resultInfoFile = resultInfoFile;

        String programPath = xml_to_dimgra_1.class.getProtectionDomain().getCodeSource().getLocation().getPath();

        try
        {
            programPath = new File(programPath).getCanonicalPath() + File.separator;
            programPath = URLDecoder.decode(programPath, "UTF-8");
        }
        catch (UnsupportedEncodingException ex)
        {
            throw constructTermination("messageCantDetermineProgramPath", ex, null);
        }
        catch (IOException ex)
        {
            throw constructTermination("messageCantDetermineProgramPath", ex, null);
        }

        File jobFile = new File(args[0]);

        try
        {
            jobFile = jobFile.getCanonicalFile();
        }
        catch (SecurityException ex)
        {
            throw constructTermination("messageJobFileCantGetCanonicalPath", ex, null, jobFile.getAbsolutePath());
        }
        catch (IOException ex)
        {
            throw constructTermination("messageJobFileCantGetCanonicalPath", ex, null, jobFile.getAbsolutePath());
        }

        if (jobFile.exists() != true)
        {
            throw constructTermination("messageJobFileDoesntExist", null, null, jobFile.getAbsolutePath());
        }

        if (jobFile.isFile() != true)
        {
            throw constructTermination("messageJobPathIsntAFile", null, null, jobFile.getAbsolutePath());
        }

        if (jobFile.canRead() != true)
        {
            throw constructTermination("messageJobFileIsntReadable", null, null, jobFile.getAbsolutePath());
        }

        System.out.println("xml_to_dimgra_1: " + getI10nStringFormatted("messageCallDetails", jobFile.getAbsolutePath(), resultInfoFile.getAbsolutePath()));

        File inputFile = null;
        File outputFile = null;
        File tempDirectory = null;
        String containerPath = null;
        String masterDimension = null;
        Map<String, StructureDefinition> structureDefinitions = new HashMap<String, StructureDefinition>();

        try
        {
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            InputStream in = new FileInputStream(jobFile);
            XMLEventReader eventReader = inputFactory.createXMLEventReader(in);

            while (eventReader.hasNext() == true)
            {
                XMLEvent event = eventReader.nextEvent();

                if (event.isStartElement() == true)
                {
                    String tagName = event.asStartElement().getName().getLocalPart();

                    if (tagName.equals("input-file") == true)
                    {
                        Attribute attributePath = event.asStartElement().getAttributeByName(new QName("path"));

                        if (attributePath == null)
                        {
                            throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null, jobFile.getAbsolutePath(), tagName, "path");
                        }

                        if (inputFile != null)
                        {
                            throw constructTermination("messageJobFileElementConfiguredMoreThanOnce", null, null, jobFile.getAbsolutePath(), tagName);
                        }

                        inputFile = new File(attributePath.getValue());

                        if (inputFile.isAbsolute() != true)
                        {
                            inputFile = new File(jobFile.getAbsoluteFile().getParent() + File.separator + attributePath.getValue());
                        }

                        try
                        {
                            inputFile = inputFile.getCanonicalFile();
                        }
                        catch (SecurityException ex)
                        {
                            throw constructTermination("messageInputFileCantGetCanonicalPath", ex, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath());
                        }
                        catch (IOException ex)
                        {
                            throw constructTermination("messageInputFileCantGetCanonicalPath", ex, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath());
                        }

                        if (inputFile.exists() != true)
                        {
                            throw constructTermination("messageInputFileDoesntExist", null, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath());
                        }

                        if (inputFile.isFile() != true)
                        {
                            throw constructTermination("messageInputPathIsntAFile", null, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath());
                        }

                        if (inputFile.canRead() != true)
                        {
                            throw constructTermination("messageInputFileIsntReadable", null, null, inputFile.getAbsolutePath(), jobFile.getAbsolutePath());
                        }
                    }
                    else if (tagName.equals("output-file") == true)
                    {
                        Attribute attributePath = event.asStartElement().getAttributeByName(new QName("path"));

                        if (attributePath == null)
                        {
                            throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null, jobFile.getAbsolutePath(), tagName, "path");
                        }

                        if (outputFile != null)
                        {
                            throw constructTermination("messageJobFileElementConfiguredMoreThanOnce", null, null, jobFile.getAbsolutePath(), tagName);
                        }

                        outputFile = new File(attributePath.getValue());

                        if (outputFile.isAbsolute() != true)
                        {
                            outputFile = new File(jobFile.getAbsoluteFile().getParent() + File.separator + attributePath.getValue());
                        }

                        try
                        {
                            outputFile = outputFile.getCanonicalFile();
                        }
                        catch (SecurityException ex)
                        {
                            throw constructTermination("messageOutputFileCantGetCanonicalPath", ex, null, outputFile.getAbsolutePath(), jobFile.getAbsolutePath());
                        }
                        catch (IOException ex)
                        {
                            throw constructTermination("messageOutputFileCantGetCanonicalPath", ex, null, outputFile.getAbsolutePath(), jobFile.getAbsolutePath());
                        }

                        if (outputFile.exists() == true)
                        {
                            if (outputFile.isFile() == true)
                            {
                                boolean deleteSuccessful = false;

                                try
                                {
                                    deleteSuccessful = outputFile.delete();
                                }
                                catch (SecurityException ex)
                                {

                                }

                                if (deleteSuccessful != true)
                                {
                                    if (outputFile.canWrite() != true)
                                    {
                                        throw constructTermination("messageOutputFileExistsButIsntWritable", null, null, outputFile.getAbsolutePath(), jobFile.getAbsolutePath());
                                    }
                                }
                            }
                            else
                            {
                                throw constructTermination("messageOutputPathExistsButIsntAFile", null, null, outputFile.getAbsolutePath(), jobFile.getAbsolutePath());
                            }
                        }
                    }
                    else if (tagName.equals("temp-directory") == true)
                    {
                        Attribute attributePath = event.asStartElement().getAttributeByName(new QName("path"));

                        if (attributePath == null)
                        {
                            throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null, jobFile.getAbsolutePath(), tagName, "path");
                        }

                        if (tempDirectory != null)
                        {
                            throw constructTermination("messageJobFileElementConfiguredMoreThanOnce", null, null, jobFile.getAbsolutePath(), tagName);
                        }

                        tempDirectory = new File(attributePath.getValue());

                        if (tempDirectory.isAbsolute() != true)
                        {
                            tempDirectory = new File(jobFile.getAbsoluteFile().getParent() + File.separator + attributePath.getValue());
                        }

                        try
                        {
                            tempDirectory = tempDirectory.getCanonicalFile();
                        }
                        catch (SecurityException ex)
                        {
                            throw constructTermination("messageTempDirectoryCantGetCanonicalPath", ex, null, tempDirectory.getAbsolutePath());
                        }
                        catch (IOException ex)
                        {
                            throw constructTermination("messageTempDirectoryCantGetCanonicalPath", ex, null, tempDirectory.getAbsolutePath());
                        }
                    }
                    else if (tagName.equals("outer-container") == true)
                    {
                        Attribute attributeOuterContainerPath = event.asStartElement().getAttributeByName(new QName("path"));

                        if (attributeOuterContainerPath == null)
                        {
                            throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null, jobFile.getAbsolutePath(), tagName, "path");
                        }

                        if (containerPath != null)
                        {
                            throw constructTermination("messageJobFileElementConfiguredMoreThanOnce", null, null, jobFile.getAbsolutePath(), tagName);
                        }

                        containerPath = attributeOuterContainerPath.getValue();

                        while (eventReader.hasNext() == true)
                        {
                            event = eventReader.nextEvent();

                            if (event.isStartElement() == true)
                            {
                                tagName = event.asStartElement().getName().getLocalPart();

                                if (tagName.equals("inner-selection") == true)
                                {
                                    StartElement elementInnerSelection = event.asStartElement();
                                    Attribute attributeInnerSelectionPath = elementInnerSelection.getAttributeByName(new QName("path"));
                                    Attribute attributeDimension = elementInnerSelection.getAttributeByName(new QName("dimension"));
                                    Attribute attributeType = elementInnerSelection.getAttributeByName(new QName("type"));

                                    if (attributeInnerSelectionPath == null)
                                    {
                                        throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null, jobFile.getAbsolutePath(), tagName, "path");
                                    }

                                    if (attributeDimension == null)
                                    {
                                        throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null, jobFile.getAbsolutePath(), tagName, "dimension");
                                    }

                                    boolean isMaster = false;

                                    if (attributeType != null)
                                    {
                                        if (attributeType.getValue().equals("master") != true)
                                        {
                                            throw constructTermination("messageJobFileEntryAttributeNotSupported", null, null, jobFile.getAbsolutePath(), tagName, "type", attributeType.getValue(), "master");
                                        }

                                        if (masterDimension != null)
                                        {
                                            throw constructTermination("messageJobFileInnerSelectionMasterConfiguredMoreThanOnce", null, null, jobFile.getAbsolutePath(), tagName, "type", "master");
                                        }

                                        isMaster = true;
                                        masterDimension = attributeDimension.getValue();
                                    }

                                    if (structureDefinitions.containsKey(attributeInnerSelectionPath.getValue()) == true)
                                    {
                                        throw constructTermination("messageJobFileInnerSelectionPathConfiguredMoreThanOnce", null, null, jobFile.getAbsolutePath(), attributeInnerSelectionPath.getValue());
                                    }

                                    /** @todo Check if a child of the outer container! Also: relative or absolute path? Also: not equal parent! */
                                    structureDefinitions.put(attributeInnerSelectionPath.getValue(),
                                                             new StructureDefinition(attributeInnerSelectionPath.getValue(), attributeDimension.getValue(), isMaster));
                                }
                            }
                            else if (event.isEndElement() == true)
                            {
                                if (event.asEndElement().getName().getLocalPart().equals("outer-container") == true)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (XMLStreamException ex)
        {
            throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath());
        }
        catch (SecurityException ex)
        {
            throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath());
        }
        catch (IOException ex)
        {
            throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath());
        }

        if (inputFile == null)
        {
            throw constructTermination("messageJobFileInputFileIsntConfigured", null, null, jobFile.getAbsolutePath(), "input-file");
        }

        if (outputFile == null)
        {
            throw constructTermination("messageJobFileOutputFileIsntConfigured", null, null, jobFile.getAbsolutePath(), "output-file");
        }

        if (containerPath == null)
        {
            throw constructTermination("messageJobFileOuterContainerIsntConfigured", null, null, jobFile.getAbsolutePath(), "outer-container");
        }

        if (structureDefinitions.size() <= 0)
        {
            throw constructTermination("messageJobFileNoInnerSelectionConfigured", null, null, jobFile.getAbsolutePath(), "inner-selection");
        }

        if (masterDimension == null)
        {
            throw constructTermination("messageJobFileNoInnerSelectionMasterConfigured", null, null, jobFile.getAbsolutePath(), "inner-selection");
        }

        if (tempDirectory == null)
        {
            tempDirectory = new File(programPath + "temp");
        }

        if (tempDirectory.exists() == true)
        {
            if (tempDirectory.isDirectory() == true)
            {
                if (tempDirectory.canWrite() != true)
                {
                    throw constructTermination("messageTempDirectoryIsntWritable", null, null, tempDirectory.getAbsolutePath());
                }
            }
            else
            {
                throw constructTermination("messageTempPathIsntADirectory", null, null, tempDirectory.getAbsolutePath());
            }
        }
        else
        {
            try
            {
                tempDirectory.mkdirs();
            }
            catch (SecurityException ex)
            {
                throw constructTermination("messageTempDirectoryCantCreate", ex, null, tempDirectory.getAbsolutePath());
            }
        }


        try
        {
            BufferedWriter writer = new BufferedWriter(
                                    new OutputStreamWriter(
                                    new FileOutputStream(outputFile),
                                    "UTF-8"));

            Stack<StructureStackElement> structureStack = new Stack<StructureStackElement>();
            StringBuilder nodeValue = null;
            Map<String, List<Node>> nodes = new HashMap<String, List<Node>>();
            Map<Long, String> edges = null;
            long nodeId = 1;
            long edgeId = 1;

            String currentInnerSelectionPathDimension = null;

            try
            {
                XMLInputFactory inputFactory = XMLInputFactory.newInstance();

                // This is a converter for generic XML, don't want to deal with legacy DTD
                // remnants. Consider using $/xml_dtd_entity_resolver/xml_dtd_entity_resolver_1.
                inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
                inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);

                InputStream in = new FileInputStream(inputFile);
                XMLEventReader eventReader = inputFactory.createXMLEventReader(in);

                while (eventReader.hasNext() == true)
                {
                    XMLEvent event = eventReader.nextEvent();

                    if (event.isStartDocument() == true)
                    {
                        writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                        writer.write("<!-- This file was created by xml_to_dimgra_1, which is free software licensed under the GNU Affero General Public License 3 or any later version (see https://gitlab.com/publishing-systems/digital_publishing_workflow_tools/ and https://publishing-systems.org). -->");
                        writer.write("<graphml xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://graphml.graphdrawing.org/xmlns\">");
                        writer.write("<key id=\"htx-scheme-id://org.hypertext-systems.20180702T071630Z/dimgra.20200601T122500Z/dimgra-1.20200601T122500Z/node-title.20200601T122500Z\" for=\"node\" attr.name=\"label\" attr.type=\"string\"/>");
                        writer.write("<key id=\"htx-scheme-id://org.hypertext-systems.20180702T071630Z/dimgra.20200601T122500Z/dimgra-1.20200601T122500Z/node-text.20200601T122500Z\" for=\"node\" attr.name=\"description\" attr.type=\"string\"/>");
                        writer.write("<key id=\"htx-scheme-id://org.hypertext-systems.20180702T071630Z/dimgra.20200601T122500Z/dimgra-1.20200601T122500Z/dimension-target.20200601T122500Z\" for=\"edge\" attr.name=\"Dimension\" attr.type=\"string\"/>");
                        writer.write("<key id=\"htx-scheme-id://org.hypertext-systems.20180702T071630Z/dimgra.20200601T122500Z/dimgra-1.20200601T122500Z/dimension-establishing.20200601T122500Z\" for=\"edge\" attr.name=\"Is establishing the dimension\" attr.type=\"boolean\"/>");
                        writer.write("<graph edgedefault=\"directed\">");
                    }
                    else if (event.isStartElement() == true)
                    {
                        String elementName = event.asStartElement().getName().getLocalPart();
                        String elementPath = "/" + elementName;

                        if (structureStack.empty() != true)
                        {
                            elementPath = structureStack.peek().getPath() + elementPath;
                        }

                        structureStack.push(new StructureStackElement(elementName, elementPath));

                        if (elementPath.equals(containerPath) == true)
                        {
                            edges = new HashMap<Long, String>();
                        }
                        else
                        {
                            if (currentInnerSelectionPathDimension != null)
                            {
                                throw constructTermination("messageInputFileNestedDimension", null, null, inputFile.getAbsolutePath(), currentInnerSelectionPathDimension);
                            }

                            Iterator<StructureDefinition> iter = structureDefinitions.values().iterator();

                            while (iter.hasNext() == true)
                            {
                                StructureDefinition structureDefinition = iter.next();

                                if (structureDefinition.getPath().equals(elementPath) == true)
                                {
                                    currentInnerSelectionPathDimension = structureDefinition.getDimension();
                                    nodeValue = new StringBuilder();
                                    break;
                                }
                            }
                        }
                    }
                    else if (event.isEndElement() == true)
                    {
                        //String elementName = event.asEndElement().getName().getLocalPart();

                        if (structureStack.empty() == true)
                        {
                            throw constructTermination("messageStructureStackIsEmptyInEndElement", null, null);
                        }

                        String elementPath = structureStack.peek().getPath();

                        if (elementPath.equals(containerPath) == true)
                        {
                            long masterId = -1;

                            for (Map.Entry<Long, String> entry : edges.entrySet())
                            {
                                if (entry.getValue().equals(masterDimension) == true)
                                {
                                    masterId = entry.getKey();
                                    break;
                                }
                            }

                            if (masterId == -1)
                            {
                                /** @todo Maybe add what the inner selection path of the master dimension is. */
                                throw constructTermination("messageInputFileOuterContainerWithoutEdgeToMasterDimension", null, null, elementPath, masterDimension);
                            }

                            for (Map.Entry<Long, String> entry : edges.entrySet())
                            {
                                if (entry.getValue().equals(masterDimension) != true)
                                {
                                    /** @todo Escaping! */
                                    writer.write("<edge id=\"edge-" + edgeId + "\" source=\"" + masterId + "\" target=\"" + entry.getKey() + "\">");
                                    writer.write("<data key=\"htx-scheme-id://org.hypertext-systems.20180702T071630Z/dimgra.20200601T122500Z/dimgra-1.20200601T122500Z/dimension-target.20200601T122500Z\">" + entry.getValue() + "</data>");
                                    writer.write("</edge>");

                                    edgeId++;
                                }
                            }

                            for (Map.Entry<Long, String> entry : edges.entrySet())
                            {
                                if (entry.getValue().equals(masterDimension) != true)
                                {
                                    /** @todo Escaping! */
                                    writer.write("<edge id=\"edge-" + edgeId + "\" source=\"" + entry.getKey() + "\" target=\"" + masterId + "\">");
                                    writer.write("<data key=\"htx-scheme-id://org.hypertext-systems.20180702T071630Z/dimgra.20200601T122500Z/dimgra-1.20200601T122500Z/dimension-target.20200601T122500Z\">" + masterDimension + "</data>");
                                    writer.write("</edge>");

                                    edgeId++;
                                }
                            }

                            edges = null;
                        }
                        else
                        {
                            if (currentInnerSelectionPathDimension != null)
                            {
                                Iterator<StructureDefinition> iter = structureDefinitions.values().iterator();

                                while (iter.hasNext() == true)
                                {
                                    StructureDefinition structureDefinition = iter.next();

                                    if (structureDefinition.getPath().equals(elementPath) == true)
                                    {
                                        String nodeValueString = nodeValue.toString();

                                        if (nodes.containsKey(currentInnerSelectionPathDimension) != true)
                                        {
                                            nodes.put(currentInnerSelectionPathDimension, new LinkedList<Node>());
                                        }

                                        long currentNodeId = -1;
                                        List<Node> list = nodes.get(currentInnerSelectionPathDimension);

                                        for (int i = 0, max = list.size(); i < max; i++)
                                        {
                                            if (list.get(i).GetValue().equals(nodeValueString) == true)
                                            {
                                                currentNodeId = list.get(i).GetId();
                                                break;
                                            }
                                        }

                                        if (currentNodeId == -1)
                                        {
                                            list.add(new Node(nodeId, nodeValueString));
                                            currentNodeId = nodeId;
                                            nodeId++;
                                        }

                                        if (edges.containsKey(currentNodeId) != true)
                                        {
                                            edges.put(currentNodeId, currentInnerSelectionPathDimension);
                                        }
                                        else
                                        {
                                            throw constructTermination("messageInputFileInnerSelectionDimensionDuplicate", null, null, currentNodeId);
                                        }

                                        currentInnerSelectionPathDimension = null;
                                        nodeValue = null;
                                        break;
                                    }
                                }

                                if (currentInnerSelectionPathDimension != null)
                                {
                                    throw constructTermination("messageInputFileInnerSelectionNotFoundInStructureDefinition", null, null, elementPath);
                                }
                            }
                        }

                        structureStack.pop();
                    }
                    else if (event.isCharacters() == true)
                    {
                        if (currentInnerSelectionPathDimension != null)
                        {
                            nodeValue.append(event.asCharacters().getData());
                        }
                    }
                    else if (event.isEndDocument() == true)
                    {
                        for (Map.Entry<String, List<Node>> entry : nodes.entrySet())
                        {
                            for (int i = 0, max = entry.getValue().size(); i < max; i++)
                            {
                                /** @todo Escaping! */
                                writer.write("<node id=\"" + entry.getValue().get(i).GetId() + "\">");
                                writer.write("<data key=\"htx-scheme-id://org.hypertext-systems.20180702T071630Z/dimgra.20200601T122500Z/dimgra-1.20200601T122500Z/node-title.20200601T122500Z\">");

                                String value = entry.getValue().get(i).GetValue();
                                // Ampersand needs to be the first, otherwise it would double-encode
                                // other entities.
                                value = value.replaceAll("&", "&amp;");
                                value = value.replaceAll("<", "&lt;");
                                value = value.replaceAll(">", "&gt;");

                                writer.write(value);
                                writer.write("</data>");
                                writer.write("</node>");
                            }
                        }

                        for (Map.Entry<String, List<Node>> entry : nodes.entrySet())
                        {
                            for (int i = 0, max = entry.getValue().size(); i < max; i++)
                            {
                                // Skip last.
                                if (i + 1 < max)
                                {
                                    /** @todo Escaping! */
                                    writer.write("<edge id=\"edge-" + edgeId + "\" source=\"" + entry.getValue().get(i).GetId() + "\" target=\"" + entry.getValue().get(i + 1).GetId() + "\">");
                                    writer.write("<data key=\"htx-scheme-id://org.hypertext-systems.20180702T071630Z/dimgra.20200601T122500Z/dimgra-1.20200601T122500Z/dimension-target.20200601T122500Z\">" + entry.getKey() + "</data>");
                                    writer.write("<data key=\"htx-scheme-id://org.hypertext-systems.20180702T071630Z/dimgra.20200601T122500Z/dimgra-1.20200601T122500Z/dimension-establishing.20200601T122500Z\">true</data>");
                                    writer.write("</edge>");
                                }

                                edgeId++;
                            }
                        }

                        writer.write("</graph>");
                        writer.write("</graphml>\n");
                    }
                }
            }
            catch (XMLStreamException ex)
            {
                throw constructTermination("messageInputFileErrorWhileReading", ex, null, inputFile.getAbsolutePath());
            }
            catch (SecurityException ex)
            {
                throw constructTermination("messageInputFileErrorWhileReading", ex, null, inputFile.getAbsolutePath());
            }
            catch (IOException ex)
            {
                throw constructTermination("messageInputFileErrorWhileReading", ex, null, inputFile.getAbsolutePath());
            }

            writer.flush();
            writer.close();
        }
        catch (FileNotFoundException ex)
        {
            throw constructTermination("messageOutputFileErrorWhileWriting", ex, null, outputFile.getAbsolutePath());
        }
        catch (UnsupportedEncodingException ex)
        {
            throw constructTermination("messageOutputFileErrorWhileWriting", ex, null, outputFile.getAbsolutePath());
        }
        catch (IOException ex)
        {
            throw constructTermination("messageOutputFileErrorWhileWriting", ex, null, outputFile.getAbsolutePath());
        }

        return 0;
    }

    public InfoMessage constructInfoMessage(String id,
                                            boolean outputToConsole,
                                            Exception exception,
                                            String message,
                                            Object ... arguments)
    {
        if (message == null)
        {
            if (arguments == null)
            {
                message = "xml_to_dimgra_1: " + getI10nString(id);
            }
            else
            {
                message = "xml_to_dimgra_1: " + getI10nStringFormatted(id, arguments);
            }
        }

        if (outputToConsole == true)
        {
            System.out.println(message);

            if (exception != null)
            {
                System.out.println(exception.getMessage());
                exception.printStackTrace();
            }
        }

        return new InfoMessage(id, exception, message, L10N_BUNDLE, arguments);
    }

    public ProgramTerminationException constructTermination(String id, Exception cause, String message, Object ... arguments)
    {
        if (message == null)
        {
            if (arguments == null)
            {
                message = "xml_to_dimgra_1: " + getI10nString(id);
            }
            else
            {
                message = "xml_to_dimgra_1: " + getI10nStringFormatted(id, arguments);
            }
        }

        return new ProgramTerminationException(id, cause, message, L10N_BUNDLE, arguments);
    }

    public int handleTermination(ProgramTerminationException ex)
    {
        String message = ex.getMessage();
        String id = ex.getId();
        String bundle = ex.getBundle();
        Object[] arguments = ex.getArguments();
        boolean normalTermination = ex.isNormalTermination();

        if (message != null)
        {
            System.err.println(message);
        }

        Throwable innerException = ex.getCause();

        if (innerException != null)
        {
            System.out.println(innerException.getMessage());
            innerException.printStackTrace();
        }

        if (xml_to_dimgra_1.resultInfoFile != null)
        {
            try
            {
                BufferedWriter writer = new BufferedWriter(
                                        new OutputStreamWriter(
                                        new FileOutputStream(xml_to_dimgra_1.resultInfoFile),
                                        "UTF-8"));

                writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
                writer.write("<!-- This file was created by xml_to_dimgra_1, which is free software licensed under the GNU Affero General Public License 3 or any later version (see https://gitlab.com/publishing-systems/digital_publishing_workflow_tools/ and https://publishing-systems.org). -->\n");
                writer.write("<xml-to-dimgra-1-result-information>\n");

                if (normalTermination == false)
                {
                    writer.write("  <failure>\n");
                }
                else
                {
                    writer.write("  <success>\n");
                }

                writer.write("    <timestamp>" + ex.getTimestamp() + "</timestamp>\n");

                if (bundle != null)
                {
                    // Ampersand needs to be the first, otherwise it would double-encode
                    // other entities.
                    bundle = bundle.replaceAll("&", "&amp;");
                    bundle = bundle.replaceAll("<", "&lt;");
                    bundle = bundle.replaceAll(">", "&gt;");

                    writer.write("    <id-bundle>" + bundle + "</id-bundle>\n");
                }

                if (id != null)
                {
                    // Ampersand needs to be the first, otherwise it would double-encode
                    // other entities.
                    id = id.replaceAll("&", "&amp;");
                    id = id.replaceAll("<", "&lt;");
                    id = id.replaceAll(">", "&gt;");

                    writer.write("    <id>" + id + "</id>\n");
                }

                if (message != null)
                {
                    // Ampersand needs to be the first, otherwise it would double-encode
                    // other entities.
                    message = message.replaceAll("&", "&amp;");
                    message = message.replaceAll("<", "&lt;");
                    message = message.replaceAll(">", "&gt;");

                    writer.write("    <message>" + message + "</message>\n");
                }

                if (arguments != null)
                {
                    writer.write("    <arguments>\n");

                    int argumentCount = arguments.length;

                    for (int i = 0; i < argumentCount; i++)
                    {
                        if (arguments[i] == null)
                        {
                            writer.write("      <argument number=\"" + i + "\">\n");
                            writer.write("        <class></class>\n");
                            writer.write("        <value>null</value>\n");
                            writer.write("      </argument>\n");

                            continue;
                        }

                        String className = arguments[i].getClass().getName();

                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        className = className.replaceAll("&", "&amp;");
                        className = className.replaceAll("<", "&lt;");
                        className = className.replaceAll(">", "&gt;");

                        String value = arguments[i].toString();

                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        value = value.replaceAll("&", "&amp;");
                        value = value.replaceAll("<", "&lt;");
                        value = value.replaceAll(">", "&gt;");

                        writer.write("      <argument number=\"" + i + "\">\n");
                        writer.write("        <class>" + className + "</class>\n");
                        writer.write("        <value>" + value + "</value>\n");
                        writer.write("      </argument>\n");
                    }

                    writer.write("    </arguments>\n");
                }

                if (innerException != null)
                {
                    writer.write("    <exception>\n");

                    String className = innerException.getClass().getName();

                    // Ampersand needs to be the first, otherwise it would double-encode
                    // other entities.
                    className = className.replaceAll("&", "&amp;");
                    className = className.replaceAll("<", "&lt;");
                    className = className.replaceAll(">", "&gt;");

                    writer.write("      <class>" + className + "</class>\n");

                    StringWriter stringWriter = new StringWriter();
                    PrintWriter printWriter = new PrintWriter(stringWriter);
                    innerException.printStackTrace(printWriter);
                    String stackTrace = stringWriter.toString();

                    // Ampersand needs to be the first, otherwise it would double-encode
                    // other entities.
                    stackTrace = stackTrace.replaceAll("&", "&amp;");
                    stackTrace = stackTrace.replaceAll("<", "&lt;");
                    stackTrace = stackTrace.replaceAll(">", "&gt;");

                    writer.write("      <stack-trace>" + stackTrace + "</stack-trace>\n");
                    writer.write("    </exception>\n");
                }

                if (this.getInfoMessages().size() > 0)
                {
                    writer.write("    <info-messages>\n");

                    for (int i = 0, max = this.getInfoMessages().size(); i < max; i++)
                    {
                        InfoMessage infoMessage = this.getInfoMessages().get(i);

                        writer.write("      <info-message>\n");
                        writer.write("        <timestamp>" + infoMessage.getTimestamp() + "</timestamp>\n");

                        String infoMessageText = infoMessage.getMessage();
                        String infoMessageId = ex.getId();
                        String infoMessageBundle = ex.getBundle();
                        Object[] infoMessageArguments = ex.getArguments();

                        if (infoMessageBundle != null)
                        {
                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            infoMessageBundle = infoMessageBundle.replaceAll("&", "&amp;");
                            infoMessageBundle = infoMessageBundle.replaceAll("<", "&lt;");
                            infoMessageBundle = infoMessageBundle.replaceAll(">", "&gt;");

                            writer.write("        <id-bundle>" + infoMessageBundle + "</id-bundle>\n");
                        }

                        if (infoMessageId != null)
                        {
                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            infoMessageId = infoMessageId.replaceAll("&", "&amp;");
                            infoMessageId = infoMessageId.replaceAll("<", "&lt;");
                            infoMessageId = infoMessageId.replaceAll(">", "&gt;");

                            writer.write("        <id>" + infoMessageId + "</id>\n");
                        }

                        if (infoMessageText != null)
                        {
                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            infoMessageText = infoMessageText.replaceAll("&", "&amp;");
                            infoMessageText = infoMessageText.replaceAll("<", "&lt;");
                            infoMessageText = infoMessageText.replaceAll(">", "&gt;");

                            writer.write("        <message>" + infoMessageText + "</message>\n");
                        }

                        if (infoMessageArguments != null)
                        {
                            writer.write("        <arguments>\n");

                            int argumentCount = infoMessageArguments.length;

                            for (int j = 0; j < argumentCount; j++)
                            {
                                if (infoMessageArguments[j] == null)
                                {
                                    writer.write("          <argument number=\"" + j + "\">\n");
                                    writer.write("            <class></class>\n");
                                    writer.write("            <value>null</value>\n");
                                    writer.write("          </argument>\n");

                                    continue;
                                }

                                String className = infoMessageArguments[j].getClass().getName();

                                // Ampersand needs to be the first, otherwise it would double-encode
                                // other entities.
                                className = className.replaceAll("&", "&amp;");
                                className = className.replaceAll("<", "&lt;");
                                className = className.replaceAll(">", "&gt;");

                                String value = infoMessageArguments[j].toString();

                                // Ampersand needs to be the first, otherwise it would double-encode
                                // other entities.
                                value = value.replaceAll("&", "&amp;");
                                value = value.replaceAll("<", "&lt;");
                                value = value.replaceAll(">", "&gt;");

                                writer.write("          <argument number=\"" + j + "\">\n");
                                writer.write("            <class>" + className + "</class>\n");
                                writer.write("            <value>" + value + "</value>\n");
                                writer.write("          </argument>\n");
                            }

                            writer.write("        </arguments>\n");
                        }

                        writer.write("      </info-message>\n");
                    }

                    writer.write("    </info-messages>\n");
                }

                if (normalTermination == false)
                {
                    writer.write("  </failure>\n");
                }
                else
                {
                    writer.write("  </success>\n");
                }

                writer.write("</xml-to-dimgra-1-result-information>\n");
                writer.flush();
                writer.close();
            }
            catch (FileNotFoundException ex2)
            {
                ex2.printStackTrace();
            }
            catch (UnsupportedEncodingException ex2)
            {
                ex2.printStackTrace();
            }
            catch (IOException ex2)
            {
                ex2.printStackTrace();
            }
        }

        xml_to_dimgra_1.resultInfoFile = null;

        System.exit(-1);
        return -1;
    }

    public List<InfoMessage> getInfoMessages()
    {
        return this.infoMessages;
    }

    public Locale getLocale()
    {
        return Locale.getDefault();
    }

    /**
     * @brief This method interprets l10n strings from a .properties file as encoded in UTF-8.
     */
    private String getI10nString(String key)
    {
        if (this.l10nConsole == null)
        {
            this.l10nConsole = ResourceBundle.getBundle(L10N_BUNDLE, this.getLocale());
        }

        try
        {
            return new String(this.l10nConsole.getString(key).getBytes("UTF-8"), "UTF-8");
        }
        catch (UnsupportedEncodingException ex)
        {
            return this.l10nConsole.getString(key);
        }
    }

    private String getI10nStringFormatted(String i10nStringName, Object ... arguments)
    {
        MessageFormat formatter = new MessageFormat("");
        formatter.setLocale(this.getLocale());

        formatter.applyPattern(getI10nString(i10nStringName));
        return formatter.format(arguments);
    }

    public static File resultInfoFile = null;
    protected List<InfoMessage> infoMessages = new ArrayList<InfoMessage>();

    private static final String L10N_BUNDLE = "l10n.l10nXmlToDimgra1Console";
    private ResourceBundle l10nConsole;
}
