// xtree internal header
#ifndef _XTREE_
#define _XTREE_
#include <functional>
#include <memory>
#include <stdexcept>

_STD_BEGIN

		// TEMPLATE CLASS _Tree_nod
template<class _Traits>
	class _Tree_nod
		: public _Traits	// traits form ultimate base
	{	// base class for _Tree_ptr to hold allocator _Alnod
protected:
	struct _Node;
	friend struct _Node;
	typedef _Node *_Nodeptr;	// _Node allocator must have ordinary pointers

	typedef typename _Traits::allocator_type allocator_type;
	typedef typename _Traits::key_compare key_compare;
	typedef typename _Traits::value_type value_type;

	struct _Node
		{	// tree node
		_Node(_Nodeptr _Larg, _Nodeptr _Parg, _Nodeptr _Rarg,
			const value_type& _Val, char _Carg)
			: _Left(_Larg), _Parent(_Parg), _Right(_Rarg),
				_Myval(_Val), _Color(_Carg), _Isnil(false)
			{	// construct a node with value
			}

		_Nodeptr _Left;	// left subtree, or smallest element if head
		_Nodeptr _Parent;	// parent, or root of tree if head
		_Nodeptr _Right;	// right subtree, or largest element if head
		value_type _Myval;	// the stored value, unused if head
		char _Color;	// _Red or _Black, _Black if head
		char _Isnil;	// true only if head (also nil) node
		};

	_Tree_nod(const key_compare& _Parg,
		allocator_type _Al)
		: _Traits(_Parg), _Alnod(_Al)
		{	// construct traits from _Parg and allocator from _Al
		}

	typename allocator_type::template rebind<_Node>::other
		_Alnod;	// allocator object for nodes
	};

		// TEMPLATE CLASS _Tree_ptr
template<class _Traits>
	class _Tree_ptr
		: public _Tree_nod<_Traits>
	{	// base class for _Tree_val to hold allocator _Alptr
public:
	typedef _Tree_nod<_Traits> _Mybase;
	typedef typename _Mybase::_Node _Node;
	typedef typename _Mybase::_Nodeptr _Nodeptr;
	typedef typename _Traits::allocator_type allocator_type;
	typedef typename _Traits::key_compare key_compare;

	_Tree_ptr(const key_compare& _Parg,
		allocator_type _Al)
		: _Tree_nod<_Traits>(_Parg, _Al), _Alptr(_Al)
		{	// construct base, and allocator from _Al
		}

	typename allocator_type::template rebind<_Nodeptr>::other
		_Alptr;	// allocator object for pointers to nodes
	};

		// TEMPLATE CLASS _Tree_val
template<class _Traits>
	class _Tree_val
		: public _Tree_ptr<_Traits>
	{	// base class for _Tree to hold allocator _Alval
protected:
	typedef typename _Traits::allocator_type allocator_type;
	typedef typename _Traits::key_compare key_compare;

	_Tree_val(const key_compare& _Parg,
		allocator_type _Al)
		: _Tree_ptr<_Traits>(_Parg, _Al), _Alval(_Al)
		{	// construct base, and allocator from _Al
		}

	allocator_type _Alval;	// allocator object for values stored in nodes
	};

		// TEMPLATE CLASS _Tree
export
template<class _Traits>
	class _Tree
		: public _Tree_val<_Traits>
	{	// ordered red-black tree for [multi_]{map set}
public:
	typedef _Tree<_Traits> _Myt;
	typedef _Tree_val<_Traits> _Mybase;
	typedef typename _Traits::key_type key_type;
	typedef typename _Traits::key_compare key_compare;
	typedef typename _Traits::value_compare value_compare;
	typedef typename _Traits::value_type value_type;
	typedef typename _Traits::allocator_type allocator_type;

 #if _HAS_IMMUTABLE_SETS
	typedef typename _Traits::_ITptr _ITptr;
	typedef typename _Traits::_IReft _IReft;

 #else /* _HAS_IMMUTABLE_SETS */
	typedef typename allocator_type::pointer _ITptr;
	typedef typename allocator_type::reference _IReft;
 #endif /* _HAS_IMMUTABLE_SETS */

protected:
	typedef typename _Mybase::_Node _Node;
	typedef typename _Mybase::_Nodeptr _Nodeptr;

	typedef typename allocator_type::template rebind<_Nodeptr>::other
		_Nodeptr_alloc;
	typedef typename _Nodeptr_alloc::reference _Nodepref;

	typedef typename allocator_type::template rebind<key_type>::other
		_Key_alloc;
	typedef typename _Key_alloc::const_reference _Keyref;

	typedef typename allocator_type::template rebind<char>::other
		_Char_alloc;
	typedef typename _Char_alloc::reference _Charref;


	typedef typename allocator_type::reference _Vref;

	enum _Redbl
		{	// colors for link to parent
		_Red, _Black};

	static _Charref _Color(_Nodeptr _Pnode)
		{	// return reference to color in node
		return ((_Charref)(*_Pnode)._Color);
		}

	static _Charref _Isnil(_Nodeptr _Pnode)
		{	// return reference to nil flag in node
		return ((_Charref)(*_Pnode)._Isnil);
		}

	static _Keyref _Key(_Nodeptr _Pnode)
		{	// return reference to key in node
		return (_Mybase::_Kfn(_Myval(_Pnode)));
		}

	static _Nodepref _Left(_Nodeptr _Pnode)
		{	// return reference to left pointer in node
		return ((_Nodepref)(*_Pnode)._Left);
		}

	static _Nodepref _Parent(_Nodeptr _Pnode)
		{	// return reference to parent pointer in node
		return ((_Nodepref)(*_Pnode)._Parent);
		}

	static _Nodepref _Right(_Nodeptr _Pnode)
		{	// return reference to right pointer in node
		return ((_Nodepref)(*_Pnode)._Right);
		}

	static _Vref _Myval(_Nodeptr _Pnode)
		{	// return reference to value in node
		return ((_Vref)(*_Pnode)._Myval);
		}

public:
	typedef typename allocator_type::size_type size_type;
	typedef typename allocator_type::difference_type _Dift;
	typedef _Dift difference_type;
	typedef typename allocator_type::pointer _Tptr;
	typedef typename allocator_type::const_pointer _Ctptr;
	typedef typename allocator_type::reference _Reft;
	typedef _Tptr pointer;
	typedef _Ctptr const_pointer;
	typedef _Reft reference;
	typedef typename allocator_type::const_reference const_reference;

		// CLASS const_iterator
	class const_iterator;
	friend class const_iterator;

	class const_iterator
		: public _Bidit<value_type, _Dift, _Ctptr, const_reference>
	{	// iterator for nonmutable _Tree
	public:
		friend class _Tree<_Traits>;
		typedef bidirectional_iterator_tag iterator_category;
		typedef _Dift difference_type;
		typedef _Ctptr pointer;
		typedef const_reference reference;

		const_iterator()
			: _Ptr(0)
			{	// construct with null node pointer
			}

 #if _HAS_ITERATOR_DEBUGGING
 #define _TREE_CONST_ITERATOR(ppnode)	const_iterator(ppnode, this)

		const_iterator(_Nodeptr _Pnode, const _Myt *_Plist)
			: _Ptr(_Pnode)
			{	// construct with node pointer _Pnode
			this->_Adopt(_Plist);
			}

 #else /* _HAS_ITERATOR_DEBUGGING */
 #define _TREE_CONST_ITERATOR(ppnode)	const_iterator(ppnode)

		const_iterator(_Nodeptr _Pnode)
			: _Ptr(_Pnode)
			{	// construct with node pointer _Pnode
			}
 #endif /* _HAS_ITERATOR_DEBUGGING */

		const_reference operator*() const
			{	// return designated value

 #if _HAS_ITERATOR_DEBUGGING
			if (this->_Mycont == 0
				|| _Ptr == ((_Myt *)this->_Mycont)->_Myhead)
				_DEBUG_ERROR("map/set iterator not dereferencable");
 #endif /* _HAS_ITERATOR_DEBUGGING */

			return (_Myval(_Ptr));
			}

		_Ctptr operator->() const
			{	// return pointer to class object
			return (&**this);
			}

		const_iterator& operator++()
			{	// preincrement
			_Inc();
			return (*this);
			}

		const_iterator operator++(int)
			{	// postincrement
			const_iterator _Tmp = *this;
			++*this;
			return (_Tmp);
			}

		const_iterator& operator--()
			{	// predecrement
			_Dec();
			return (*this);
			}

		const_iterator operator--(int)
			{	// postdecrement
			const_iterator _Tmp = *this;
			--*this;
			return (_Tmp);
			}

		bool operator==(const const_iterator& _Right) const
			{	// test for iterator equality

 #if _HAS_ITERATOR_DEBUGGING
			if (this->_Mycont == 0 || this->_Mycont != _Right._Mycont)
				_DEBUG_ERROR("map/set iterators incompatible");
 #endif /* _HAS_ITERATOR_DEBUGGING */

			return (_Ptr == _Right._Ptr);
			}

		bool operator!=(const const_iterator& _Right) const
			{	// test for iterator inequality
			return (!(*this == _Right));
			}

		void _Dec()
			{	// move to node with next smaller value

 #if _HAS_ITERATOR_DEBUGGING
			if (this->_Mycont == 0)
				_DEBUG_ERROR("map/set iterator not decrementable");
 #endif /* _HAS_ITERATOR_DEBUGGING */

			if (_Isnil(_Ptr))
				_Ptr = _Right(_Ptr);	// end() ==> rightmost
			else if (!_Isnil(_Left(_Ptr)))
				_Ptr = _Max(_Left(_Ptr));	// ==> largest of left subtree
			else
				{	// climb looking for left subtree
				_Nodeptr _Pnode;
				while (!_Isnil(_Pnode = _Parent(_Ptr))
					&& _Ptr == _Left(_Pnode))
					_Ptr = _Pnode;	// ==> parent while left subtree
				if (_Isnil(_Ptr))

 #if _HAS_ITERATOR_DEBUGGING
					_DEBUG_ERROR("map/set iterator not decrementable");

 #else /* _HAS_ITERATOR_DEBUGGING */
					return;	// begin() shouldn't be incremented, don't move
 #endif /* _HAS_ITERATOR_DEBUGGING */

				else
					_Ptr = _Pnode;	// ==> parent if not head
				}
			}

		void _Inc()
			{	// move to node with next larger value

 #if _HAS_ITERATOR_DEBUGGING
			if (this->_Mycont == 0 || _Isnil(_Ptr))
				_DEBUG_ERROR("map/set iterator not incrementable");

 #else /* _HAS_ITERATOR_DEBUGGING */
			if (_Isnil(_Ptr))
				;	// end() shouldn't be incremented, don't move
 #endif /* _HAS_ITERATOR_DEBUGGING */

			else if (!_Isnil(_Right(_Ptr)))
				_Ptr = _Min(_Right(_Ptr));	// ==> smallest of right subtree
			else
				{	// climb looking for right subtree
				_Nodeptr _Pnode;
				while (!_Isnil(_Pnode = _Parent(_Ptr))
					&& _Ptr == _Right(_Pnode))
					_Ptr = _Pnode;	// ==> parent while right subtree
				_Ptr = _Pnode;	// ==> parent (head if end())
				}
			}

		_Nodeptr _Mynode() const
			{	// return node pointer
			return (_Ptr);
			}

protected:
		_Nodeptr _Ptr;	// pointer to node
		};

		// CLASS iterator
	class iterator;
	friend class iterator;

	class iterator
		: public const_iterator
	{	// iterator for mutable _Tree
	public:
		typedef bidirectional_iterator_tag iterator_category;
		typedef _Dift difference_type;
		typedef _ITptr pointer;
		typedef _IReft reference;

		iterator()
			{	// construct with null node pointer
			}

 #if _HAS_ITERATOR_DEBUGGING
 #define _TREE_ITERATOR(ppnode)	iterator(ppnode, this)

		iterator(_Nodeptr _Pnode, const _Myt *_Plist)
			: const_iterator(_Pnode, _Plist)
			{	// construct with node pointer _Pnode
			}

 #else /* _HAS_ITERATOR_DEBUGGING */
 #define _TREE_ITERATOR(ppnode)	iterator(ppnode)

		iterator(_Nodeptr _Pnode)
			: const_iterator(_Pnode)
			{	// construct with node pointer _Pnode
			}
 #endif /* _HAS_ITERATOR_DEBUGGING */

		reference operator*() const
			{	// return designated value
			return ((reference)**(const_iterator *)this);
			}

		pointer operator->() const
			{	// return pointer to class object
			return (&**this);
			}

		iterator& operator++()
			{	// preincrement
			++(*(const_iterator *)this);
			return (*this);
			}

		iterator operator++(int)
			{	// postincrement
			iterator _Tmp = *this;
			++*this;
			return (_Tmp);
			}

		iterator& operator--()
			{	// predecrement
			--(*(const_iterator *)this);
			return (*this);
			}

		iterator operator--(int)
			{	// postdecrement
			iterator _Tmp = *this;
			--*this;
			return (_Tmp);
			}
		};

	typedef _STD reverse_iterator<iterator> reverse_iterator;
	typedef _STD reverse_iterator<const_iterator> const_reverse_iterator;
	typedef pair<iterator, bool> _Pairib;
	typedef pair<iterator, iterator> _Pairii;
	typedef pair<const_iterator, const_iterator> _Paircc;

	explicit _Tree(const key_compare& _Parg,
		const allocator_type& _Al)
		: _Mybase(_Parg, _Al)
		{	// construct empty tree
		_Init();
		}

	_Tree(const value_type *_First, const value_type *_Last,
		const key_compare& _Parg, const allocator_type& _Al);

	_Tree(const _Myt& _Right);

	~_Tree()
		{	// destroy tree
		_Tidy();
		}

	_Myt& operator=(const _Myt& _Right)
		{	// replace contents from _Right
		if (this != &_Right)
			{	// worth doing
			erase(begin(), end());
			this->comp = _Right.comp;
			_Copy(_Right);
			}
		return (*this);
		}

	iterator begin()
		{	// return iterator for beginning of mutable sequence
		return (_TREE_ITERATOR(_Lmost()));
		}

	const_iterator begin() const
		{	// return iterator for beginning of nonmutable sequence
		return (_TREE_CONST_ITERATOR(_Lmost()));
		}

	iterator end()
		{	// return iterator for end of mutable sequence
		return (_TREE_ITERATOR(_Myhead));
		}

	const_iterator end() const
		{	// return iterator for end of nonmutable sequence
		return (_TREE_CONST_ITERATOR(_Myhead));
		}

	reverse_iterator rbegin()
		{	// return iterator for beginning of reversed mutable sequence
		return (reverse_iterator(end()));
		}

	const_reverse_iterator rbegin() const
		{	// return iterator for beginning of reversed nonmutable sequence
		return (const_reverse_iterator(end()));
		}

	reverse_iterator rend()
		{	// return iterator for end of reversed mutable sequence
		return (reverse_iterator(begin()));
		}

	const_reverse_iterator rend() const
		{	// return iterator for end of reversed nonmutable sequence
		return (const_reverse_iterator(begin()));
		}

	size_type size() const
		{	// return length of sequence
		return (_Mysize);
		}

	size_type max_size() const
		{	// return maximum possible length of sequence
		return (this->_Alval.max_size());
		}

	bool empty() const
		{	// return true only if sequence is empty
		return (size() == 0);
		}

	allocator_type get_allocator() const
		{	// return allocator object for values
		return (this->_Alval);
		}

	key_compare key_comp() const
		{	// return object for comparing keys
		return (this->comp);
		}

	value_compare value_comp() const
		{	// return object for comparing values
		return (value_compare(key_comp()));
		}

	_Pairib insert(const value_type& _Val);

	iterator insert(iterator _Where,
		const value_type& _Val);

	template<class _Iter>
		void insert(_Iter _First, _Iter _Last);

	iterator erase(iterator _Where);

	iterator erase(iterator _First, iterator _Last);

	size_type erase(const key_type& _Keyval);

	void erase(const key_type *_First, const key_type *_Last)
		{	// erase all that match array of keys [_First, _Last)
		_DEBUG_RANGE(_First, _Last);
		while (_First != _Last)
			erase(*_First++);
		}

	void clear()
		{	// erase all

 #if _HAS_ITERATOR_DEBUGGING
		this->_Orphan_ptr(*this, 0);
 #endif /* _HAS_ITERATOR_DEBUGGING */

		_Erase(_Root());
		_Root() = _Myhead, _Mysize = 0;
		_Lmost() = _Myhead, _Rmost() = _Myhead;
		}

	iterator find(const key_type& _Keyval)
		{	// find an element in mutable sequence that matches _Keyval
		iterator _Where = lower_bound(_Keyval);
		return (_Where == end()
			|| _DEBUG_LT_PRED(this->comp,
				_Keyval, _Key(_Where._Mynode()))
					? end() : _Where);
		}

	const_iterator find(const key_type& _Keyval) const
		{	// find an element in nonmutable sequence that matches _Keyval
		const_iterator _Where = lower_bound(_Keyval);
		return (_Where == end()
			|| _DEBUG_LT_PRED(this->comp,
				_Keyval, _Key(_Where._Mynode()))
					? end() : _Where);
		}

	size_type count(const key_type& _Keyval) const
		{	// count all elements that match _Keyval
		_Paircc _Ans = equal_range(_Keyval);
		size_type _Num = 0;
		_Distance(_Ans.first, _Ans.second, _Num);
		return (_Num);
		}

	iterator lower_bound(const key_type& _Keyval)
		{	// find leftmost node not less than _Keyval in mutable tree
		return (_TREE_ITERATOR(_Lbound(_Keyval)));
		}

	const_iterator lower_bound(const key_type& _Keyval) const
		{	// find leftmost node not less than _Keyval in nonmutable tree
		return (_TREE_CONST_ITERATOR(_Lbound(_Keyval)));
		}

	iterator upper_bound(const key_type& _Keyval)
		{	// find leftmost node greater than _Keyval in mutable tree
		return (_TREE_ITERATOR(_Ubound(_Keyval)));
		}

	const_iterator upper_bound(const key_type& _Keyval) const
		{	// find leftmost node greater than _Keyval in nonmutable tree
		return (_TREE_CONST_ITERATOR(_Ubound(_Keyval)));
		}

	_Pairii equal_range(const key_type& _Keyval)
		{	// find range equivalent to _Keyval in mutable tree
		return (_Eqrange(_Keyval));
		}

	_Paircc equal_range(const key_type& _Keyval) const
		{	// find range equivalent to _Keyval in nonmutable tree
		return (_Eqrange(_Keyval));
		}

	void swap(_Myt& _Right)
		{	// exchange contents with _Right
		if (this == &_Right)
			;	// same object, do nothing
		else if (get_allocator() == _Right.get_allocator())
			{	// same allocator, swap control information

 #if _HAS_ITERATOR_DEBUGGING
			this->_Swap_all(_Right);
 #endif /* _HAS_ITERATOR_DEBUGGING */

			_STD swap(this->comp, _Right.comp);
			_STD swap(_Myhead, _Right._Myhead);
			_STD swap(_Mysize, _Right._Mysize);
			}
		else
			{	// different allocator, do multiple assigns
			_Myt _Tmp = *this;

			*this = _Right;
			_Right = _Tmp;
			}
		}

protected:
	void _Copy(const _Myt& _Right);

	_Nodeptr _Copy(_Nodeptr _Rootnode, _Nodeptr _Wherenode);

	_Paircc _Eqrange(const key_type& _Keyval) const;

	_Pairii _Eqrange(const key_type& _Keyval);

	void _Erase(_Nodeptr _Rootnode);

	void _Init()
		{	// create head/nil node and make tree empty
		_Myhead = _Buynode();
		_Isnil(_Myhead) = true;
		_Root() = _Myhead;
		_Lmost() = _Myhead, _Rmost() = _Myhead;
		_Mysize = 0;
		}

	iterator _Insert(bool _Addleft, _Nodeptr _Wherenode,
		const value_type& _Val);

	_Nodeptr _Lbound(const key_type& _Keyval) const;

	_Nodeptr& _Lmost() const
		{	// return leftmost node in nonmutable tree
		return (_Left(_Myhead));
		}

	void _Lrotate(_Nodeptr _Wherenode);

	static _Nodeptr _Max(_Nodeptr _Pnode)
		{	// return rightmost node in subtree at _Pnode
		while (!_Isnil(_Right(_Pnode)))
			_Pnode = _Right(_Pnode);
		return (_Pnode);
		}

	static _Nodeptr _Min(_Nodeptr _Pnode)
		{	// return leftmost node in subtree at _Pnode
		while (!_Isnil(_Left(_Pnode)))
			_Pnode = _Left(_Pnode);
		return (_Pnode);
		}

	_Nodeptr& _Rmost() const
		{	// return rightmost node in nonmutable tree
		return (_Right(_Myhead));
		}

	_Nodeptr& _Root() const
		{	// return root of nonmutable tree
		return (_Parent(_Myhead));
		}

	void _Rrotate(_Nodeptr _Wherenode);

	_Nodeptr _Ubound(const key_type& _Keyval) const;

 #if _HAS_ITERATOR_DEBUGGING
	void _Orphan_ptr(_Myt& _Cont, _Nodeptr _Ptr) const
		{	// orphan iterators with specified node pointers
		_Lockit _Lock(_LOCK_DEBUG);
		const_iterator **_Pnext = (const_iterator **)&_Cont._Myfirstiter;
		while (*_Pnext != 0)
			if ((*_Pnext)->_Ptr == _Myhead
				|| _Ptr != 0 && (*_Pnext)->_Ptr != _Ptr)
				_Pnext = (const_iterator **)&(*_Pnext)->_Mynextiter;
			else
				{	// orphan the iterator
				(*_Pnext)->_Mycont = 0;
				*_Pnext = (const_iterator *)(*_Pnext)->_Mynextiter;
				}
		}
 #endif /* _HAS_ITERATOR_DEBUGGING */

	_Nodeptr _Buynode();

	_Nodeptr _Buynode(_Nodeptr _Larg, _Nodeptr _Parg,
		_Nodeptr _Rarg, const value_type& _Val, char _Carg);

	void _Tidy();

	_Nodeptr _Myhead;	// pointer to head node
	size_type _Mysize;	// number of elements
	};

		// _Tree TEMPLATE OPERATORS
template<class _Traits> inline
	bool operator==(const _Tree<_Traits>& _Left, const _Tree<_Traits>& _Right)
	{	// test for _Tree equality
	return (_Left.size() == _Right.size()
		&& equal(_Left.begin(), _Left.end(), _Right.begin()));
	}

template<class _Traits> inline
	bool operator!=(const _Tree<_Traits>& _Left, const _Tree<_Traits>& _Right)
	{	// test for _Tree inequality
	return (!(_Left == _Right));
	}

template<class _Traits> inline
	bool operator<(const _Tree<_Traits>& _Left, const _Tree<_Traits>& _Right)
	{	// test if _Less < _Right for _Trees
	return (lexicographical_compare(_Left.begin(), _Left.end(),
		_Right.begin(), _Right.end()));
	}

template<class _Traits> inline
	bool operator>(const _Tree<_Traits>& _Left, const _Tree<_Traits>& _Right)
	{	// test if _Less > _Right for _Trees
	return (_Right < _Left);
	}

template<class _Traits> inline
	bool operator<=(const _Tree<_Traits>& _Left, const _Tree<_Traits>& _Right)
	{	// test if _Less <= _Right for _Trees
	return (!(_Right < _Left));
	}

template<class _Traits> inline
	bool operator>=(const _Tree<_Traits>& _Left, const _Tree<_Traits>& _Right)
	{	// test if _Less >= _Right for _Trees
	return (!(_Left < _Right));
	}
_STD_END
#endif /* _XTREE_ */

/*
 * Copyright (c) 1992-2006 by P.J. Plauger.  ALL RIGHTS RESERVED.
 * Consult your license regarding permissions and restrictions.
 */

/*
 * This file is derived from software bearing the following
 * restrictions:
 *
 * Copyright (c) 1994
 * Hewlett-Packard Company
 *
 * Permission to use, copy, modify, distribute and sell this
 * software and its documentation for any purpose is hereby
 * granted without fee, provided that the above copyright notice
 * appear in all copies and that both that copyright notice and
 * this permission notice appear in supporting documentation.
 * Hewlett-Packard Company makes no representations about the
 * suitability of this software for any purpose. It is provided
 * "as is" without express or implied warranty.
V5.01:1566 */
