/*******************************************************************\

              Copyright (C) 2002, 2003 Joseph Coffland

    This program is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
        of the License, or (at your option) any later version.

   This program 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 General Public License for more details.

  You should have received a copy of the GNU General Public License
     along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
                           02111-1307, USA.

            For information regarding this software email
                   jcofflan@users.sourceforge.net

\*******************************************************************/

#include "XMLCompare.h"

#include <xercesc/dom/DOM.hpp>
XERCES_CPP_NAMESPACE_USE;

#include <BasicUtils/BasicException.h>


bool xmlCompareNodeList(DOMNodeList *list1, DOMNodeList *list2,
			unsigned int index1, unsigned int index2) {
  ASSERT_OR_THROW("xmlCompareNodeList() NULL pointer error!", list1 && list2);
			
  if (index1 == list1->getLength() && index2 == list2->getLength())
    return true;

  // Skip comments and processing instructions
  if (index1 < list1->getLength()) {
    DOMNode *item1 = list1->item(index1);

    if (item1->getNodeType() == DOMNode::COMMENT_NODE ||
	item1->getNodeType() == DOMNode::PROCESSING_INSTRUCTION_NODE)
      return xmlCompareNodeList(list1, list2, index1 + 1, index2);
  }

  if (index2 < list2->getLength()) {
    DOMNode *item2 = list2->item(index2);

    if (item2->getNodeType() == DOMNode::COMMENT_NODE ||
	item2->getNodeType() == DOMNode::PROCESSING_INSTRUCTION_NODE)
      return xmlCompareNodeList(list1, list2, index1, index2 + 1);
  }

  if (index1 == list1->getLength() || index2 == list2->getLength())
    return false;

  if (!xmlCompare(list1->item(index1), list2->item(index2)))
    return false;

  return xmlCompareNodeList(list1, list2, index1 + 1, index2 + 1);
}


bool xmlCompare(DOMNode *node1, DOMNode *node2) {
  ASSERT_OR_THROW("xmlCompare() NULL pointer error!", node1 && node2);

  // Compare node types
  if (node1->getNodeType() != node2->getNodeType()) return false;

  // Compare node value
    if (XMLString::compareString(node1->getNodeValue(), node2->getNodeValue()))
      return false;

  // Compare node names
  if (XMLString::compareString(node1->getNodeName(), node2->getNodeName()))
    return false;

  // Compare children
  return xmlCompareNodeList(node1->getChildNodes(), node2->getChildNodes());
}
