File: XdmfWriter.cpp

package info (click to toggle)
xdmf 3.0%2Bgit20160803-3
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 35,388 kB
  • ctags: 36,627
  • sloc: ansic: 265,382; cpp: 162,889; python: 10,976; f90: 1,378; yacc: 687; fortran: 464; xml: 200; java: 187; lex: 125; makefile: 82; sh: 28
file content (842 lines) | stat: -rw-r--r-- 27,907 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
/*****************************************************************************/
/*                                    XDMF                                   */
/*                       eXtensible Data Model and Format                    */
/*                                                                           */
/*  Id : XdmfWriter.cpp                                                      */
/*                                                                           */
/*  Author:                                                                  */
/*     Kenneth Leiter                                                        */
/*     kenneth.leiter@arl.army.mil                                           */
/*     US Army Research Laboratory                                           */
/*     Aberdeen Proving Ground, MD                                           */
/*                                                                           */
/*     Copyright @ 2011 US Army Research Laboratory                          */
/*     All Rights Reserved                                                   */
/*     See Copyright.txt for details                                         */
/*                                                                           */
/*     This software is distributed WITHOUT ANY WARRANTY; without            */
/*     even the implied warranty of MERCHANTABILITY or FITNESS               */
/*     FOR A PARTICULAR PURPOSE.  See the above copyright notice             */
/*     for more information.                                                 */
/*                                                                           */
/*****************************************************************************/

#include <fstream>
#include <libxml/tree.h>
#include <sstream>
#include <utility>
#include "XdmfArray.hpp"
#include "XdmfInformation.hpp"
#include "XdmfHeavyDataWriter.hpp"
#include "XdmfHDF5Controller.hpp"
#include "XdmfHDF5Writer.hpp"
#include "XdmfItem.hpp"
#include "XdmfSystemUtils.hpp"
#include "XdmfWriter.hpp"
#include "XdmfVersion.hpp"
#include "XdmfError.hpp"
#include "string.h"

/**
 * PIMPL
 */
class XdmfWriter::XdmfWriterImpl {

public:

  XdmfWriterImpl(const std::string & xmlFilePath,
                 const shared_ptr<XdmfHeavyDataWriter> heavyDataWriter,
                 std::ostream * stream) :
    mDepth(0),
    mDocumentTitle("Xdmf"),
    mHeavyDataWriter(heavyDataWriter),
    mHeavyWriterIsOpen(false),
    mLastXPathed(false),
    mLightDataLimit(100),
    mMode(Default),
    mStream(stream),
    mWriteXPaths(true),
    mXPathParse(true),
    mXMLCurrentNode(NULL),
    mXMLDocument(NULL),
    mXMLFilePath(XdmfSystemUtils::getRealPath(xmlFilePath)),
    mXPathCount(0),
    mXPathString(""),
    mVersionString(XdmfVersion.getShort())
  {
  };

  ~XdmfWriterImpl()
  {
  };

  void
  closeFile()
  {
    mXPath.clear();
    mXPathCount = 0;

    // This section writes to file
    std::ofstream fileStream;
    if(!mStream) {
      fileStream.open(mXMLFilePath.c_str());
      mStream = &fileStream;
    }

    xmlBufferPtr buffer = xmlBufferCreate();
    xmlOutputBuffer * outputBuffer = xmlOutputBufferCreateBuffer(buffer,
                                                                 NULL);
    xmlSaveFormatFileTo(outputBuffer,
                        mXMLDocument,
                        "utf-8",
                        1);
    *mStream << buffer->content;
    xmlBufferFree(buffer);
    
    if(fileStream.is_open()) {
      fileStream.close();
      mStream = NULL;
    }
    
//    xmlFreeDoc(mXMLDocument);
    xmlCleanupParser();

    if(mHeavyDataWriter->getMode() == XdmfHeavyDataWriter::Default) {
      if (mHeavyWriterIsOpen) {
        mHeavyDataWriter->closeFile();
      }
    }
  };

  void
  openFile()
  {
    mXMLDocument = xmlNewDoc((xmlChar*)"1.0");
    mXMLCurrentNode = xmlNewNode(NULL, (xmlChar*)mDocumentTitle.c_str());
    xmlNewProp(mXMLCurrentNode,
               (xmlChar*)"xmlns:xi",
               (xmlChar*)"http://www.w3.org/2001/XInclude");
    xmlNewProp(mXMLCurrentNode,
               (xmlChar*)"Version",
               (xmlChar*)mVersionString.c_str());
    xmlDocSetRootElement(mXMLDocument, mXMLCurrentNode);
  }

  int mDepth;
  std::string mDocumentTitle;
  shared_ptr<XdmfHeavyDataWriter> mHeavyDataWriter;
  bool mHeavyWriterIsOpen;
  bool mLastXPathed;
  unsigned int mLightDataLimit;
  Mode mMode;
  std::ostream * mStream;
  bool mWriteXPaths;
  bool mXPathParse;
  xmlNodePtr mXMLCurrentNode;
  xmlDocPtr mXMLDocument;
  std::string mXMLFilePath;
  std::map<const XdmfItem * const, std::string> mXPath;
  unsigned int mXPathCount;
  std::string mXPathString;
  std::string mVersionString;

};

shared_ptr<XdmfWriter>
XdmfWriter::New(const std::string & xmlFilePath)
{
  std::stringstream heavyFileName;
  size_t extension = xmlFilePath.rfind(".");
  if(extension != std::string::npos) {
    heavyFileName << xmlFilePath.substr(0, extension) << ".h5";
  }
  else {
    heavyFileName << xmlFilePath << ".h5";
  }
  shared_ptr<XdmfHDF5Writer> hdf5Writer = 
    XdmfHDF5Writer::New(heavyFileName.str());
  shared_ptr<XdmfWriter> p(new XdmfWriter(xmlFilePath, hdf5Writer));
  return p;
}

shared_ptr<XdmfWriter>
XdmfWriter::New(const std::string & xmlFilePath,
                const shared_ptr<XdmfHeavyDataWriter> heavyDataWriter)
{
  shared_ptr<XdmfWriter> p(new XdmfWriter(xmlFilePath,
                                          heavyDataWriter));
  return p;
}

shared_ptr<XdmfWriter> 
XdmfWriter::New(std::ostream & stream,
                const shared_ptr<XdmfHeavyDataWriter> heavyDataWriter)
{
  shared_ptr<XdmfWriter> p(new XdmfWriter("",
                                          heavyDataWriter,
                                          &stream));
  return p;
}

XdmfWriter::XdmfWriter(const std::string & xmlFilePath,
                       shared_ptr<XdmfHeavyDataWriter> heavyDataWriter,
                       std::ostream * stream) :
  mRebuildAlreadyVisited(true),
  mImpl(new XdmfWriterImpl(xmlFilePath, 
                           heavyDataWriter,
                           stream))
{
}

XdmfWriter::XdmfWriter(const XdmfWriter & writerRef) :
  mRebuildAlreadyVisited(writerRef.mRebuildAlreadyVisited)
{
  char * transferPath = strdup(writerRef.getFilePath().c_str());
  char * heavyTransferPath = strdup(writerRef.getHeavyDataWriter()->getFilePath().c_str());
  mImpl = new XdmfWriterImpl(transferPath, XdmfHDF5Writer::New(heavyTransferPath), NULL);
}

XdmfWriter::~XdmfWriter()
{
  mXMLArchive.clear();
  xmlFreeDoc(mImpl->mXMLDocument);
  delete mImpl;
}

shared_ptr<XdmfHeavyDataWriter>
XdmfWriter::getHeavyDataWriter()
{
  return boost::const_pointer_cast<XdmfHeavyDataWriter>
    (static_cast<const XdmfWriter &>(*this).getHeavyDataWriter());
}

shared_ptr<const XdmfHeavyDataWriter>
XdmfWriter::getHeavyDataWriter() const
{
  return mImpl->mHeavyDataWriter;
}

std::string
XdmfWriter::getFilePath() const
{
  return mImpl->mXMLFilePath;
}

unsigned int
XdmfWriter::getLightDataLimit() const
{
  return mImpl->mLightDataLimit;
}

XdmfWriter::Mode
XdmfWriter::getMode() const
{
  return mImpl->mMode;
}

bool
XdmfWriter::getRebuildXML()
{
  return mRebuildAlreadyVisited;
}

xmlNodePtr
XdmfWriter::getXMLNode(XdmfItem * item, xmlDocPtr parentDoc, xmlNodePtr parentNode)
{
  std::map<XdmfItem *, xmlNodePtr>::iterator node =
    mXMLArchive.find(item);
  if (node != mXMLArchive.end())
  {
    xmlAddChild(parentNode, mXMLArchive[item]);
    return mXMLArchive[item];
  }
  else
  {
    return xmlNewNode(NULL, (xmlChar*)"NULL");
  }
}

bool
XdmfWriter::getHasXMLArchive(XdmfItem * item)
{
  std::map<XdmfItem *, xmlNodePtr>::iterator node =
    mXMLArchive.find(item);
  if (node != mXMLArchive.end())
  {
    return true;
  }
  else
  {
    return false;
  }
}

bool
XdmfWriter::getWriteXPaths() const
{
  return mImpl->mWriteXPaths;
}

bool
XdmfWriter::getXPathParse() const
{
  return mImpl->mXPathParse;
}

void
XdmfWriter::setDocumentTitle(std::string title)
{
  mImpl->mDocumentTitle = title;
}

void
XdmfWriter::setHeavyDataWriter(shared_ptr<XdmfHeavyDataWriter> heavyDataWriter)
{
  mImpl->mHeavyDataWriter = heavyDataWriter;
}

void
XdmfWriter::setLightDataLimit(const unsigned int numValues)
{
  mImpl->mLightDataLimit = numValues;
}

void
XdmfWriter::setMode(const Mode mode)
{
  mImpl->mMode = mode;
}

void
XdmfWriter::setRebuildXML(bool newStatus)
{
  mRebuildAlreadyVisited = newStatus;
}

void
XdmfWriter::setVersionString(std::string version)
{
  mImpl->mVersionString = version;
}

void
XdmfWriter::setXMLNode(XdmfItem * item, xmlNodePtr & newNode)
{
    mXMLArchive[item] = xmlCopyNode(newNode, 1);
}

void
XdmfWriter::setWriteXPaths(const bool writeXPaths)
{
  mImpl->mWriteXPaths = writeXPaths;
}

void
XdmfWriter::setXPathParse(const bool xPathParse)
{
  mImpl->mXPathParse = xPathParse;
}

void
XdmfWriter::visit(XdmfArray & array,
                  const shared_ptr<XdmfBaseVisitor> visitor)
{
  if (mImpl->mDepth == 0) {
    mImpl->openFile();
  }
  mImpl->mDepth++;

  // Pull the Function and Subset accociated with the array
  shared_ptr<XdmfArrayReference> internalReference = array.getReference();

  // If in the correct read mode process the function or subset
  // if it exists
  if (internalReference && array.getReadMode() == XdmfArray::Reference) {
    // Pass information about the array to the function
    // so it can properly recreate it when read
    internalReference->setConstructedType(array.getItemTag());
    internalReference->setConstructedProperties(array.getItemProperties());
    internalReference->accept(visitor);
    // This does not write the data contained within the array to file
    // The data is regenerated upon read
  }
  else if (array.getReadMode() == XdmfArray::Controller) {
    // Controller mode is the default mode
    const bool isSubclassed = 
      array.getItemTag().compare(XdmfArray::ItemTag) != 0;

    if(isSubclassed) {
      this->visit(dynamic_cast<XdmfItem &>(array), visitor);
    }

    if(array.getSize() > 0 && !(mImpl->mLastXPathed && isSubclassed)) {
      std::vector<std::string> xmlTextValues;

      // Take care of writing to single heavy data file (Default behavior)
      if(!array.isInitialized() && array.getHeavyDataController(0) &&
         array.getHeavyDataController(0)->getFilePath().compare(mImpl->mHeavyDataWriter->getFilePath()) != 0 &&
         mImpl->mMode == Default) {
        array.read();
      }

      if(array.getHeavyDataController(0) ||
         array.getSize() > mImpl->mLightDataLimit) {
        // Write values to heavy data

        // This takes about half the time needed
        if ((!mImpl->mHeavyWriterIsOpen) &&
            mImpl->mHeavyDataWriter->getMode() == XdmfHeavyDataWriter::Default) {
          mImpl->mHeavyDataWriter->openFile();
          mImpl->mHeavyWriterIsOpen = true;
        }
        mImpl->mHeavyDataWriter->visit(array, mImpl->mHeavyDataWriter);

        std::stringstream valuesStream;
        for(unsigned int i = 0; i < array.getNumberHeavyDataControllers(); ++i) {

          std::string heavyDataPath =
            array.getHeavyDataController(i)->getFilePath();
          size_t index = heavyDataPath.find_last_of("/\\");
          if(index != std::string::npos) {
            // If path is not a folder
            // put the directory path into this variable
            const std::string heavyDataDir = heavyDataPath.substr(0, index + 1);
            // If the directory is in the XML File Path
            if(mImpl->mXMLFilePath.find(heavyDataDir) == 0) {
              heavyDataPath =
                heavyDataPath.substr(heavyDataDir.size(),
                                     heavyDataPath.size() - heavyDataDir.size());
              // Pull the file off of the end and place it in the DataPath
            }
            // Otherwise the full path is required
          }
          // Clear the stream
          valuesStream.str(std::string());
          valuesStream << heavyDataPath << array.getHeavyDataController(i)->getDescriptor();
          if (array.getNumberHeavyDataControllers() > 1 ||
              (array.getHeavyDataController(i)->getSize() !=
               array.getHeavyDataController(i)->getDataspaceSize())) {
            valuesStream << "|" << array.getHeavyDataController(i)->getDataspaceDescription();
            if (i + 1 < array.getNumberHeavyDataControllers()) {
              valuesStream << "|";
            }
          }
          xmlTextValues.push_back(valuesStream.str());
        }
      }
      else {
        // Write values to XML
        xmlTextValues.push_back(array.getValuesString());
      }

      bool oldWriteXPaths = mImpl->mWriteXPaths;

      // Write XML (metadata) description
      if(isSubclassed) {
        // We don't want temporary items to be on the XPath List
        // This is a one-of anyway, so it shouldn't be equivalent
        // to anything written before now or after.
        mImpl->mWriteXPaths = false;
        const unsigned int parentCount = mImpl->mXPathCount;
        mImpl->mXPathCount = 0;
        shared_ptr<XdmfArray> arrayToWrite = XdmfArray::New();
        array.swap(arrayToWrite);
        mImpl->mXMLCurrentNode = mImpl->mXMLCurrentNode->last;
        this->visit(dynamic_cast<XdmfItem &>(*arrayToWrite.get()), visitor);
        for(unsigned int i = 0; i<xmlTextValues.size(); ++i) {
          xmlAddChild(mImpl->mXMLCurrentNode->last,
                      xmlNewText((xmlChar*)xmlTextValues[i].c_str()));
        }
        mImpl->mXMLCurrentNode = mImpl->mXMLCurrentNode->parent;
        array.swap(arrayToWrite);
        mImpl->mXPathCount = parentCount;
        mImpl->mLastXPathed = false;
      }
      else {
        std::map<const XdmfItem * const, std::string>::const_iterator iter =
          mImpl->mXPath.find(&array);
        this->visit(dynamic_cast<XdmfItem &>(array), visitor);
        if(iter == mImpl->mXPath.end()) {
          for(unsigned int i = 0; i<xmlTextValues.size(); ++i) {
            xmlAddChild(mImpl->mXMLCurrentNode->last,
                        xmlNewText((xmlChar*)xmlTextValues[i].c_str()));
          }
        }
      }
      mImpl->mWriteXPaths = oldWriteXPaths;
    }
  }
  else {
    // These statements are reached when an unsupported read mode is used
    // or when a read mode is not properly set up
    if (array.getReadMode() == XdmfArray::Reference) {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Array to be output as an array reference"
                         " does not have an associated reference.");
    }
    else {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Invalid output type.");
    }
  }

  mImpl->mDepth--;
  if(mImpl->mDepth <= 0) {
    mImpl->closeFile();
  }
}

void
XdmfWriter::visit(XdmfItem & item,
                  const shared_ptr<XdmfBaseVisitor> visitor)
{
  if (mImpl->mDepth == 0) {
    mImpl->openFile();
  }
  mImpl->mDepth++;

  if ((item.getItemTag().compare("Grid") != 0) || // If not a grid
      (item.getItemTag().compare("Grid") == 0 && item.getIsChanged()) || // If a Grid that is changed
      (item.getItemTag().compare("Grid") == 0 && !getHasXMLArchive(&item)) || // If the grid doesn't have an XML Archive
      mRebuildAlreadyVisited) // If Rebuild
  {
    std::string tag = item.getItemTag();
    if (tag.length() == 0) {
      item.traverse(visitor);
    }
    else {
      if(mImpl->mWriteXPaths) {
        if (tag == "Information" && mImpl->mXPathParse) {
          XdmfInformation & xpathinfo = dynamic_cast<XdmfInformation &>(item);
          if (xpathinfo.getKey() == "XIncludes") {
            shared_ptr<XdmfInformation> outputinfo;
            for (unsigned int i = 0; i < xpathinfo.getNumberInformations(); ++i) {
              mImpl->mXPathCount++;
              outputinfo = xpathinfo.getInformation(i);
              mImpl->mXMLCurrentNode = xmlNewChild(mImpl->mXMLCurrentNode,
                                                   NULL,
                                                   (xmlChar*)"xi:include",
                                                   NULL);
              xmlNewProp(mImpl->mXMLCurrentNode,
                         (xmlChar*)"href",
                         (xmlChar*)(outputinfo->getKey().c_str()));
              xmlNewProp(mImpl->mXMLCurrentNode,
                         (xmlChar*)"xpointer",
                         (xmlChar*)(outputinfo->getValue().c_str()));
              if (i < xpathinfo.getNumberInformations()-1) {
                mImpl->mXMLCurrentNode = mImpl->mXMLCurrentNode->parent;
              }
            }
          }
          else {
            mImpl->mXPathCount++;

            const std::string parentXPathString = mImpl->mXPathString;

            std::stringstream newXPathString;
            newXPathString << mImpl->mXPathString << "/" << mImpl->mXPathCount;
            mImpl->mXPathString = newXPathString.str();

            std::map<const XdmfItem * const, std::string>::const_iterator iter =
              mImpl->mXPath.find(&item);
            if(iter != mImpl->mXPath.end()) {
              // Inserted before --- just xpath location of previously written node
              mImpl->mXMLCurrentNode = xmlNewChild(mImpl->mXMLCurrentNode,
                                                   NULL,
                                                   (xmlChar*)"xi:include",
                                                   NULL);
              xmlNewProp(mImpl->mXMLCurrentNode,
                         (xmlChar*)"xpointer",
                         (xmlChar*)iter->second.c_str());
              mImpl->mLastXPathed = true;
            }
            else {
              // Not inserted before --- need to write all data and traverse.
              mImpl->mXMLCurrentNode = xmlNewChild(mImpl->mXMLCurrentNode,
                                                   NULL,
                                                   (xmlChar *)tag.c_str(),
                                                   NULL);
              std::stringstream xPathProp;
              xPathProp << "element(/1" << mImpl->mXPathString << ")";
              mImpl->mXPath.insert(std::make_pair(&item, xPathProp.str()));
              const std::map<std::string, std::string> & itemProperties =
                item.getItemProperties();
              for(std::map<std::string, std::string>::const_iterator iter =
                  itemProperties.begin();
                  iter != itemProperties.end();
                  ++iter) {
                xmlNewProp(mImpl->mXMLCurrentNode,
                           (xmlChar*)iter->first.c_str(),
                           (xmlChar*)iter->second.c_str());
              }
              const unsigned int parentCount = mImpl->mXPathCount;
              mImpl->mXPathCount = 0;
              item.traverse(visitor);
              mImpl->mXPathCount = parentCount;
              mImpl->mLastXPathed = false;
            }

            mImpl->mXPathString = parentXPathString;

          }
        }
        else {
          mImpl->mXPathCount++;

          const std::string parentXPathString = mImpl->mXPathString;

          std::stringstream newXPathString;
          newXPathString << mImpl->mXPathString << "/" << mImpl->mXPathCount;
          mImpl->mXPathString = newXPathString.str();

          std::map<const XdmfItem * const, std::string>::const_iterator iter =
          mImpl->mXPath.find(&item);
          if(iter != mImpl->mXPath.end()) {
            // Inserted before --- just xpath location of previously written node
            mImpl->mXMLCurrentNode = xmlNewChild(mImpl->mXMLCurrentNode,
                                                 NULL,
                                                 (xmlChar*)"xi:include",
                                                 NULL);
           xmlNewProp(mImpl->mXMLCurrentNode,
                      (xmlChar*)"xpointer",
                      (xmlChar*)iter->second.c_str());
           mImpl->mLastXPathed = true;
          }
          else {
            // Not inserted before --- need to write all data and traverse.

            mImpl->mXMLCurrentNode = xmlNewChild(mImpl->mXMLCurrentNode,
                                                 NULL,
                                                 (xmlChar *)tag.c_str(),
                                                 NULL);
            std::stringstream xPathProp;
            xPathProp << "element(/1" << mImpl->mXPathString << ")";
            mImpl->mXPath.insert(std::make_pair(&item, xPathProp.str()));
            const std::map<std::string, std::string> & itemProperties =
            item.getItemProperties();
            for(std::map<std::string, std::string>::const_iterator iter =
                itemProperties.begin();
                iter != itemProperties.end();
                ++iter) {
              xmlNewProp(mImpl->mXMLCurrentNode,
                         (xmlChar*)iter->first.c_str(),
                         (xmlChar*)iter->second.c_str());
            }
            const unsigned int parentCount = mImpl->mXPathCount;
            mImpl->mXPathCount = 0;
            item.traverse(visitor);
            mImpl->mXPathCount = parentCount;
            mImpl->mLastXPathed = false;
          }
          mImpl->mXPathString = parentXPathString;
        }
      }
      else
      {
        // Increment XPathCount, handling temporary arrays not written to XPath
        mImpl->mXPathCount++;
        // Not inserted before --- need to write all data and traverse.
        mImpl->mXMLCurrentNode = xmlNewChild(mImpl->mXMLCurrentNode,
                                             NULL,
                                             (xmlChar*)tag.c_str(),
                                             NULL);
        const std::map<std::string, std::string> itemProperties =
          item.getItemProperties();
        for(std::map<std::string, std::string>::const_iterator iter =
              itemProperties.begin();
            iter != itemProperties.end();
            ++iter) {
          xmlNewProp(mImpl->mXMLCurrentNode,
                     (xmlChar*)iter->first.c_str(),
                     (xmlChar*)iter->second.c_str());
        }
        const unsigned int parentCount = mImpl->mXPathCount;
        mImpl->mXPathCount = 0;
        item.traverse(visitor);
        mImpl->mXPathCount = parentCount;
        mImpl->mLastXPathed = false;
      }

      if (!mRebuildAlreadyVisited)
      {
        if (item.getItemTag().compare("Grid") == 0)
        {
          setXMLNode(&item, mImpl->mXMLCurrentNode);
        }
        item.setIsChanged(false);
      }

      mImpl->mXMLCurrentNode = mImpl->mXMLCurrentNode->parent;
    }
  }
  else
  {
    std::map<const XdmfItem * const, std::string>::const_iterator iter =
      mImpl->mXPath.find(&item);
    if(iter != mImpl->mXPath.end()) {
      // Inserted before --- just xpath location of previously written node
      mImpl->mXMLCurrentNode = xmlNewChild(mImpl->mXMLCurrentNode,
                                           NULL,
                                           (xmlChar*)"xi:include",
                                           NULL);
      xmlNewProp(mImpl->mXMLCurrentNode,
                 (xmlChar*)"xpointer",
                 (xmlChar*)iter->second.c_str());
      mImpl->mXMLCurrentNode = mImpl->mXMLCurrentNode->parent;
    }
    else {
      this->getXMLNode(&item, mImpl->mXMLDocument, mImpl->mXMLCurrentNode);
    }
  }

  mImpl->mDepth--;
  if(mImpl->mDepth <= 0) {
    mImpl->closeFile();
  }
}

// C Wrappers

XDMFWRITER * XdmfWriterNew(char * fileName)
{
  try
  {
    shared_ptr<XdmfWriter> generatedWriter = XdmfWriter::New(std::string(fileName));
    return (XDMFWRITER *)((void *)(new XdmfWriter(*generatedWriter.get())));
  }
  catch (...)
  {
    shared_ptr<XdmfWriter> generatedWriter = XdmfWriter::New(std::string(fileName));
    return (XDMFWRITER *)((void *)(new XdmfWriter(*generatedWriter.get())));
  }
}

XDMFWRITER * XdmfWriterNewSpecifyHeavyDataWriter(char * fileName, XDMFHEAVYDATAWRITER * heavyDataWriter)
{
  try
  {
    shared_ptr<XdmfWriter> generatedWriter = XdmfWriter::New(std::string(fileName), shared_ptr<XdmfHeavyDataWriter>((XdmfHeavyDataWriter *) heavyDataWriter));
    return (XDMFWRITER *)((void *)(new XdmfWriter(*generatedWriter.get())));
  }
  catch (...)
  {
    shared_ptr<XdmfWriter> generatedWriter = XdmfWriter::New(std::string(fileName), shared_ptr<XdmfHeavyDataWriter>((XdmfHeavyDataWriter *) heavyDataWriter));
    return (XDMFWRITER *)((void *)(new XdmfWriter(*generatedWriter.get())));
  }
}

void XdmfWriterFree(XDMFWRITER * item)
{
  if (item != NULL) {
    delete ((XdmfWriter *)item);
    item = NULL;
  }
}

char * XdmfWriterGetFilePath(XDMFWRITER * writer, int * status)
{
  XDMF_ERROR_WRAP_START(status)
  char * returnPointer = strdup(((XdmfWriter *)writer)->getFilePath().c_str());
  return returnPointer;
  XDMF_ERROR_WRAP_END(status)
  return NULL;
}

XDMFHEAVYDATAWRITER * XdmfWriterGetHeavyDataWriter(XDMFWRITER * writer, int * status)
{
  XDMF_ERROR_WRAP_START(status)
  return (XDMFHEAVYDATAWRITER *)((void *)(((XdmfWriter *)writer)->getHeavyDataWriter().get()));
  XDMF_ERROR_WRAP_END(status)
  return NULL;
}

unsigned int XdmfWriterGetLightDataLimit(XDMFWRITER * writer, int * status)
{
  XDMF_ERROR_WRAP_START(status)
  return ((XdmfWriter *)writer)->getLightDataLimit();
  XDMF_ERROR_WRAP_END(status)
  return 0;
}

int XdmfWriterGetMode(XDMFWRITER * writer, int * status)
{
  XDMF_ERROR_WRAP_START(status)
  XdmfWriter::Mode testMode = ((XdmfWriter *)writer)->getMode();
  if (testMode == XdmfWriter::Default) {
    return XDMF_WRITER_MODE_DEFAULT;
  }
  else if (testMode == XdmfWriter::DistributedHeavyData) {
    return XDMF_WRITER_MODE_DISTRIBUTED_HEAVY_DATA;
  }
  else {
    return -1;
  }
  XDMF_ERROR_WRAP_END(status)
  return -1;
}

int XdmfWriterGetWriteXPaths(XDMFWRITER * writer, int * status)
{
  XDMF_ERROR_WRAP_START(status)
  return ((XdmfWriter *)writer)->getWriteXPaths();
  XDMF_ERROR_WRAP_END(status)
  return 0;
}

int XdmfWriterGetXPathParse(XDMFWRITER * writer, int * status)
{
  XDMF_ERROR_WRAP_START(status)
  return ((XdmfWriter *)writer)->getXPathParse();
  XDMF_ERROR_WRAP_END(status)
  return 0;
}

void XdmfWriterSetHeavyDataWriter(XDMFWRITER * writer, XDMFHEAVYDATAWRITER * heavyDataWriter, int transferOwnership, int * status)
{
  XDMF_ERROR_WRAP_START(status)
  if (transferOwnership) {
    ((XdmfWriter *)writer)->setHeavyDataWriter(shared_ptr<XdmfHeavyDataWriter>((XdmfHeavyDataWriter *) heavyDataWriter));
  }
  else {
    ((XdmfWriter *)writer)->setHeavyDataWriter(shared_ptr<XdmfHeavyDataWriter>((XdmfHeavyDataWriter *) heavyDataWriter, XdmfNullDeleter()));
  }
  XDMF_ERROR_WRAP_END(status)
}

void XdmfWriterSetLightDataLimit(XDMFWRITER * writer, unsigned int numValues, int * status)
{
  XDMF_ERROR_WRAP_START(status)
  ((XdmfWriter *)writer)->setLightDataLimit(numValues);
  XDMF_ERROR_WRAP_END(status)
}

void XdmfWriterSetMode(XDMFWRITER * writer, int mode, int * status)
{
  XDMF_ERROR_WRAP_START(status)
  switch (mode) {
    case XDMF_WRITER_MODE_DEFAULT:
      ((XdmfWriter *)writer)->setMode(XdmfWriter::Default);
      break;
    case XDMF_WRITER_MODE_DISTRIBUTED_HEAVY_DATA:
      ((XdmfWriter *)writer)->setMode(XdmfWriter::DistributedHeavyData);
      break;
    default:
      XdmfError::message(XdmfError::FATAL,
                         "Error: Invalid writer mode.");
  }
  XDMF_ERROR_WRAP_END(status)
}

void XdmfWriterSetWriteXPaths(XDMFWRITER * writer, int writeXPaths, int * status)
{
  XDMF_ERROR_WRAP_START(status)
  ((XdmfWriter *)writer)->setWriteXPaths(writeXPaths);
  XDMF_ERROR_WRAP_END(status)
}

void XdmfWriterSetXPathParse(XDMFWRITER * writer, int xPathParse, int * status)
{
  XDMF_ERROR_WRAP_START(status)
  ((XdmfWriter *)writer)->setXPathParse(xPathParse);
  XDMF_ERROR_WRAP_END(status)
}