/*
 * Copyright (c) 1997,1998
 * Silicon Graphics Computer Systems, Inc.
 *
 * Copyright (c) 1999 
 * Boris Fomitchev
 *
 * This material is provided "as is", with absolutely no warranty expressed
 * or implied. Any use is at your own risk.
 *
 * Permission to use or copy this software for any purpose is hereby granted 
 * without fee, provided the above notices are retained on all copies.
 * Permission to modify the code and to distribute modified code is granted,
 * provided the above notices are retained, and a notice that the code was
 * modified is included with the above copyright notice.
 *
 */

#ifndef __SGI_STL_STRING
#define __SGI_STL_STRING

#include <stl_config.h>

#ifdef __STL_USE_NATIVE_STRING

# if defined (__STL_MSVC)
// lower #ifdef level
#  include <use_ansi.h>
#  include <streambuf>
#  include <istream>
# endif

// STLport uses native string if new iostreams are being used, 
// as part of compiled runtime library depends on it.
// Edit relative path below (or put full path) to get native <string> included.
// DO NOT use SGI <string> with native <iostream> unless you recompile 
// standard C++ runtime library with STLport installed. 
#  include __STL_NATIVE_HEADER(string)

# endif /* __STL_USE_NATIVE_STRING */

# if !defined (__STL_USE_NATIVE_STRING) || defined (__STL_USE_OWN_NAMESPACE)

#if defined (__STL_USE_NEW_STYLE_HEADERS)
# include <cctype>
#else
# include <ctype.h>
#endif
#include <functional>
// #include <char_traits.h>  // This header name is an extension.
#include <stl_string_fwd.h>
#include <stdexcept>      
#include <stl_iterator_base.h>
#include <memory>
#include <algorithm>
#include <iosfwd>

#if defined( __MWERKS__ ) && ! defined (__STL_USE_OWN_NAMESPACE)

// MSL implementation classes expect to see the definition of streampos
// when this header is included. We expect this to be fixed in later MSL
// implementations
# include <mcompile.h>
# if !defined( __MSL_CPP__ ) || __MSL_CPP__ < 0x4105
#  include <msl_string.h>
# endif

#endif // __MWERKS__

// Standard C++ string class.  This class has performance
// characteristics very much like vector<>, meaning, for example, that
// it does not perform reference-count or copy-on-write, and that
// concatenation of two strings is an O(N) operation. 

// There are three reasons why basic_string is not identical to
// vector.  First, basic_string always stores a null character at the
// end; this makes it possible for c_str to be a fast operation.
// Second, the C++ standard requires basic_string to copy elements
// using char_traits<>::assign, char_traits<>::copy, and
// char_traits<>::move.  This means that all of vector<>'s low-level
// operations must be rewritten.  Third, basic_string<> has a lot of
// extra functions in its interface that are convenient but, strictly
// speaking, redundant.

// Additionally, the C++ standard imposes a major restriction: according
// to the standard, the character type _CharT must be a POD type.  This
// implementation weakens that restriction, and allows _CharT to be a
// a user-defined non-POD type.  However, _CharT must still have a
// default constructor.

__STL_BEGIN_NAMESPACE

#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma set woff 1174
#pragma set woff 1375
#endif

// A helper class to use a char_traits as a function object.

template <class _Traits>
struct _Not_within_traits
  : public unary_function<typename _Traits::char_type, bool>
{
  typedef typename _Traits::char_type _CharT;
  const _CharT* _M_first;
  const _CharT* _M_last;

  _Not_within_traits(const typename _Traits::char_type* __f, 
		     const typename _Traits::char_type* __l) 
    : _M_first(__f), _M_last(__l) {}

  bool operator()(const typename _Traits::char_type& __x) const {
    return find_if((_CharT*)_M_first, (_CharT*)_M_last, 
                   bind1st(_Eq_traits<_Traits>(), __x)) == (_CharT*)_M_last;
  }
};

# if defined (__STL_DEBUG)

template <class _Tp, class _Ref, class _Ptr>
struct _String_iterator;

template <class _Tp,  class _Ref, class _Ptr>
bool __Dereferenceable(const  _String_iterator<_Tp, _Ref, _Ptr>& __that);
template <class _Tp,  class _Ref, class _Ptr>
bool __Nonsingular(const  _String_iterator<_Tp, _Ref, _Ptr>& __that);

template <class _Tp, class _Ref, class _Ptr>
struct _String_iterator : public __owned_link {
private:
    typedef _String_iterator<_Tp,_Ref, _Ptr> _Self;
    typedef _String_iterator<_Tp,_Tp&, _Tp*> iterator;
    typedef _String_iterator<_Tp,const _Tp&, const _Tp*> const_iterator;
public:
    typedef _Tp value_type;
    typedef _Ptr pointer;
    typedef _Ref reference;
    typedef ptrdiff_t difference_type;
    typedef random_access_iterator_tag iterator_category;
    pointer _M_iterator;
public:
    _String_iterator() : __owned_link(0)  {}
    _String_iterator(const __owned_list* __c, pointer __it) :
        __owned_link(__c), _M_iterator(__it) {}
    _String_iterator(const iterator& __it) :
        __owned_link(__it), _M_iterator(__it._Get_iterator()) {}
    ~_String_iterator() {}
    pointer  _Get_iterator() const { return _M_iterator; }
# if 0
  // Here, we are using different policy than in other containers,
  // as we expect lots of code assuming string::iterator is pointer. 
    operator pointer()  const { 
      __stl_debug_check(_Valid());
      return _M_iterator; 
    }
# endif
    bool _Dereferenceable() const {
      return __Dereferenceable(*this);
    }
    bool _Nonsingular() const {
      return __Nonsingular(*this);
    }
    reference operator*() const {
        __stl_debug_check(_Dereferenceable());
        return *_M_iterator;
    }
#ifndef __SGI_STL_NO_ARROW_OPERATOR
    pointer operator->() const { return &(operator*()); }
#endif /* __SGI_STL_NO_ARROW_OPERATOR */
    _Self& operator++() {
        ++_M_iterator;
        __stl_debug_check(_Nonsingular());
        return *this;
    }
    _Self operator++(int) {
        _Self __tmp = *this;
        ++_M_iterator;
        return __tmp;
    }
    _Self& operator--() {
        --_M_iterator;
        __stl_debug_check(_Nonsingular());
        return *this;
    }
    _Self operator--(int) {
        _Self __tmp = *this;
        --_M_iterator;
        return __tmp;
    }
    difference_type operator-(const _Self& __y ) const {
      __stl_debug_check(__check_same_owner(*this, __y));
      return _Get_iterator()-__y._Get_iterator();
    }
    _Self& operator+=(difference_type __n) {
        _M_iterator+=__n;
        __stl_debug_check(_Nonsingular());
        return *this;
    }
    _Self& operator-=(difference_type __n) {
    return *this+=-__n;
    }
    _Self operator+(difference_type __n) const {
        _Self __tmp(*this);
        return __tmp += __n;
    }
    _Self operator-(difference_type __n) const {
        _Self __tmp(*this);
        return __tmp -= __n;
    }
    bool operator==(const _Self& __y) const {
      __stl_debug_check(__check_same_owner_or_null(*this, __y));
      return _Get_iterator()==__y._Get_iterator();
    }
    bool operator!=(const _Self& __y ) const {
      __stl_debug_check(__check_same_owner_or_null(*this, __y));
      return _Get_iterator()!=__y._Get_iterator();
    }
    bool operator<(const _Self& __y ) const {
      __stl_debug_check(__check_same_owner(*this, __y));
      return _Get_iterator()<__y._Get_iterator();
    }
    reference operator[](difference_type __n) const { return *(*this + __n); }
};

template <class _Tp, class _Ref, class _Ptr>
inline _String_iterator<_Tp, _Ref, _Ptr> 
operator+(ptrdiff_t __n, const _String_iterator<_Tp, _Ref, _Ptr>& __it) {
    _String_iterator<_Tp, _Ref, _Ptr> __tmp(__it);
    return __tmp += __n;
}

#  if !defined (__STL_CLASS_PARTIAL_SPECIALIZATION)
template <class _Tp, class _Ref, class _Ptr>
inline _Tp* 
value_type(const  _String_iterator<_Tp, _Ref, _Ptr>&) { return (_Tp*) 0; }
template <class _Tp, class _Ref, class _Ptr>
inline ptrdiff_t* 
distance_type(const  _String_iterator<_Tp, _Ref, _Ptr>&) { return (ptrdiff_t*) 0; }
template <class _Tp, class _Ref, class _Ptr>
inline random_access_iterator_tag
iterator_category(const _String_iterator<_Tp, _Ref, _Ptr>&) { 
    return random_access_iterator_tag();
}
#  endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */

template <class _Tp,  class _Ref, class _Ptr>
bool __Dereferenceable(const  _String_iterator<_Tp, _Ref, _Ptr>& __that) {
    __stl_verbose_return(__that._Valid(), __STL_MSG_INVALID_ITERATOR);
    _Tp* const * __start = (_Tp* const *)(__that._Owner()->_Owner());
    __stl_verbose_return((__that._Get_iterator() < *(__start+1)) && 
                         (__that._Get_iterator() >= *__start),
                          __STL_MSG_NOT_DEREFERENCEABLE);    
    return true;
}

template <class _Tp,  class _Ref, class _Ptr>
bool __Nonsingular(const  _String_iterator<_Tp, _Ref, _Ptr>& __that) {
  __stl_verbose_return(__that._Valid(), __STL_MSG_INVALID_ITERATOR);
  _Tp* const * __start = (_Tp* const *)(__that._Owner()->_Owner());
  __stl_verbose_return((__that._Get_iterator() <= *(__start+1)) && 
		       (__that._Get_iterator() >= *__start),
		       __STL_MSG_SINGULAR_ITERATOR);    
    return true;
}

# endif /* __STL_DEBUG */


// ------------------------------------------------------------
// Class _String_base.  

// _String_base is a helper class that makes it it easier to write an
// exception-safe version of basic_string.  The constructor allocates,
// but does not initialize, a block of memory.  The destructor
// deallocates, but does not destroy elements within, a block of
// memory.  The destructor assumes that _M_start either is null, or else
// points to a block of memory that was allocated using _String_base's 
// allocator and whose size is _M_end_of_storage - _M_start.

// Additionally, _String_base encapsulates the difference between
// old SGI-style allocators and standard-conforming allocators.

#ifdef __STL_USE_STD_ALLOCATORS

// General base class.
template <class _Tp, class _Alloc, bool _S_instanceless>
class _String_alloc_base {
public:
  typedef typename _Alloc_traits<_Tp, _Alloc>::allocator_type allocator_type;
  allocator_type get_allocator() const { return _M_data_allocator; }

  _String_alloc_base(const allocator_type& __a)
    : _M_data_allocator(__a), _M_start(0), _M_finish(0), _M_end_of_storage(0)
    {}

protected:
  _Tp* _M_allocate(size_t __n)
    { return _M_data_allocator.allocate(__n); }
  void _M_deallocate(_Tp* __p, size_t __n) {
    if (__p)
      _M_data_allocator.deallocate(__p, __n); 
  }

protected:
  allocator_type _M_data_allocator;

  _Tp* _M_start;
  _Tp* _M_finish;
  _Tp* _M_end_of_storage;
};

// Specialization for instanceless allocators.
template <class _Tp, class _Alloc>
class _String_alloc_base<_Tp,_Alloc,true> {
public:
  typedef typename _Alloc_traits<_Tp, _Alloc>::allocator_type allocator_type;
  allocator_type get_allocator() const { return allocator_type(); }

  _String_alloc_base(const allocator_type&)
    : _M_start(0), _M_finish(0), _M_end_of_storage(0) {}

protected:
  typedef typename _Alloc_traits<_Tp, _Alloc>::_Alloc_type _Alloc_type;
  _Tp* _M_allocate(size_t __n)
    { return _Alloc_type::allocate(__n); }
  void _M_deallocate(_Tp* __p, size_t __n)
    { _Alloc_type::deallocate(__p, __n); }

protected:
  _Tp* _M_start;
  _Tp* _M_finish;
  _Tp* _M_end_of_storage;
};

template <class _Tp, class _Alloc>
class _String_base 
  : public _String_alloc_base<_Tp, _Alloc,
                              _Alloc_traits<_Tp, _Alloc>::_S_instanceless>
{
  //protected:
public:
  typedef _String_alloc_base<_Tp, _Alloc,
                             _Alloc_traits<_Tp, _Alloc>::_S_instanceless>
          _Base;
#if defined( __STL_HAS_NAMESPACES )
  __STL_USING_BASE_MEMBER _String_alloc_base<_Tp, _Alloc,
                             _Alloc_traits<_Tp, _Alloc>::_S_instanceless>::_M_start;
  __STL_USING_BASE_MEMBER _String_alloc_base<_Tp, _Alloc,
                             _Alloc_traits<_Tp, _Alloc>::_S_instanceless>::_M_finish;
  __STL_USING_BASE_MEMBER _String_alloc_base<_Tp, _Alloc,
                             _Alloc_traits<_Tp, _Alloc>::_S_instanceless>::_M_end_of_storage;
  __STL_USING_BASE_MEMBER _String_alloc_base<_Tp, _Alloc,
                             _Alloc_traits<_Tp, _Alloc>::_S_instanceless>::_M_allocate;
  __STL_USING_BASE_MEMBER _String_alloc_base<_Tp, _Alloc,
                             _Alloc_traits<_Tp, _Alloc>::_S_instanceless>::_M_deallocate;
#endif /* __STL_HAS_NAMESPACES */
  typedef typename _Base::allocator_type allocator_type;

  void _M_allocate_block(size_t __n) { 
    if (__n <= max_size()) {
      _M_start  = _M_allocate(__n);
      _M_finish = _M_start;
      _M_end_of_storage = _M_start + __n;
    }
    else
      _M_throw_length_error();
  }

  void _M_deallocate_block() 
    { _M_deallocate(_M_start, _M_end_of_storage - _M_start); }
  
  size_t max_size() const { return (size_t(-1) / sizeof(_Tp)) - 1; }

  _String_base(const allocator_type& __a) : _Base(__a) { }
  
  _String_base(const allocator_type& __a, size_t __n) : _Base(__a)
    { _M_allocate_block(__n); }

  ~_String_base() { _M_deallocate_block(); }

  void _M_throw_length_error() const;
  void _M_throw_out_of_range() const;
};

#else /* __STL_USE_STD_ALLOCATORS */

template <class _Tp, class _Alloc> class _String_base {
public:
  typedef _Alloc allocator_type;
  allocator_type get_allocator() const { return allocator_type(); }

  // protected:
  typedef simple_alloc<_Tp, _Alloc> _Alloc_type;

  _Tp* _M_start;
  _Tp* _M_finish;
  _Tp* _M_end_of_storage;
                                // Precondition: 0 < __n <= max_size().

  _Tp* _M_allocate(size_t __n) { return _Alloc_type::allocate(__n); }
  void _M_deallocate(_Tp* __p, size_t __n) {
    if (__p)
      _Alloc_type::deallocate(__p, __n); 
  }

  void _M_allocate_block(size_t __n) { 
    if (__n <= max_size()) {
      _M_start  = _M_allocate(__n);
      _M_finish = _M_start;
      _M_end_of_storage = _M_start + __n;
    }
    else
      _M_throw_length_error();
  }

  void _M_deallocate_block() 
    { _M_deallocate(_M_start, _M_end_of_storage - _M_start); }
  
  size_t max_size() const { return (size_t(-1) / sizeof(_Tp)) - 1; }

  _String_base(const allocator_type&)
    : _M_start(0), _M_finish(0), _M_end_of_storage(0) { }
  
  _String_base(const allocator_type&, size_t __n)
    : _M_start(0), _M_finish(0), _M_end_of_storage(0)
    { _M_allocate_block(__n); }

  ~_String_base() { _M_deallocate_block(); }

  void _M_throw_length_error() const;
  void _M_throw_out_of_range() const;
};

#endif /* __STL_USE_STD_ALLOCATORS */

# if defined (__STL_DEBUG)
#  define _Make_iterator(__i) iterator(&_M_iter_list, __i)
#  define _Make_const_iterator(__i) const_iterator(&_M_iter_list, __i)
#  define _Make_ptr(__i)   __i._Get_iterator()
# else
#  define _Make_iterator(__i) __i
#  define _Make_const_iterator(__i) __i
#  define _Make_ptr(__i)   __i
# endif

// ------------------------------------------------------------
// Class basic_string.  

// Class invariants:
// (1) [start, finish) is a valid range.
// (2) Each iterator in [start, finish) points to a valid object
//     of type value_type.
// (3) *finish is a valid object of type value_type; in particular,
//     it is value_type().
// (4) [finish + 1, end_of_storage) is a valid range.
// (5) Each iterator in [finish + 1, end_of_storage) points to 
//     unininitialized memory.

// Note one important consequence: a string of length n must manage
// a block of memory whose size is at least n + 1.  

struct _String_reserve_t {};

template <class _CharT, class _Traits, class _Alloc> 
class basic_string : protected _String_base<_CharT,_Alloc> {
private:                        // Protected members inherited from base.
  typedef _String_base<_CharT,_Alloc> _Base;
  typedef basic_string<_CharT, _Traits, _Alloc> _Self;
  // fbp : used to optimize char/wchar_t cases, and to simplify
  // __STL_DEFAULT_CONSTRUCTOR_BUG problem workaround
  typedef typename _Is_integer<_CharT>::_Integral _Char_Is_Integral;
protected:
#if defined( __STL_HAS_NAMESPACES )
  __STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_allocate;
  __STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_deallocate;
  __STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_allocate_block;
# ifndef __STL_DEBUG
  __STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_deallocate_block;
# endif
  __STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_throw_length_error;
  __STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_throw_out_of_range;

  __STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_start;
  __STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_finish;
  __STL_USING_BASE_MEMBER _String_base<_CharT,_Alloc>::_M_end_of_storage;
#endif /* __STL_HAS_NAMESPACES */
public:
  typedef _CharT value_type;
  typedef _Traits traits_type;

  typedef value_type* pointer;
  typedef const value_type* const_pointer;
  typedef value_type& reference;
  typedef const value_type& const_reference;
  typedef size_t size_type;
  typedef ptrdiff_t difference_type;

# if defined (__STL_DEBUG)
  typedef _String_iterator<_CharT,_CharT&, _CharT*> iterator;
  typedef _String_iterator<_CharT,const _CharT&, const _CharT*> const_iterator;
private:
  mutable __owned_list _M_iter_list;
public:
# else
  typedef const value_type*                const_iterator;
  typedef value_type*                      iterator;
# endif

#if defined ( __STL_CLASS_PARTIAL_SPECIALIZATION ) && \
! defined (__STL_PARTIAL_SPECIALIZATION_BUG)
  typedef __STD::reverse_iterator<const_iterator> const_reverse_iterator;
  typedef __STD::reverse_iterator<iterator> reverse_iterator;
#else /* __STL_CLASS_PARTIAL_SPECIALIZATION */
# if defined (__STL_MSVC50_COMPATIBILITY)
  typedef __STD::reverse_iterator<const_iterator, value_type, const_reference, 
    const_pointer, difference_type>  const_reverse_iterator;
  typedef __STD::reverse_iterator<iterator, value_type, reference, pointer, difference_type>
    reverse_iterator;
# else
  typedef __STD::reverse_iterator<const_iterator, value_type, const_reference, 
    difference_type>  const_reverse_iterator;
  typedef __STD::reverse_iterator<iterator, value_type, reference, difference_type>
    reverse_iterator;
# endif
#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */

  static const size_type npos;
  typedef _String_reserve_t _Reserve_t;
# ifdef __STL_USE_OWN_NAMESPACE
  // this typedef is being used for conversions
  typedef __STL_VENDOR_STD::basic_string<_CharT,_Traits, 
    __STL_VENDOR_STD::allocator<_CharT> >  __std_string;
# endif
  
public:                         // Constructor, destructor, assignment.
  typedef typename _Base::allocator_type allocator_type;
  allocator_type get_allocator() const { return _Base::get_allocator(); }

  basic_string()
    : _String_base<_CharT,_Alloc>(allocator_type(), 8) { 
            __stl_debug_do(_M_iter_list._Safe_init(&_M_start));
	    _M_terminate_string(); 
  }

  explicit basic_string(const allocator_type& __a)
    : _String_base<_CharT,_Alloc>(__a, 8) { 
    __stl_debug_do(_M_iter_list._Safe_init(&_M_start));
    _M_terminate_string(); 
  }

  basic_string(_Reserve_t, size_t __n,
               const __STL_ALLOC_PARAM& __a = __STL_ALLOC_INSTANCE(__STL_ALLOC_PARAM))
    : _String_base<_CharT,_Alloc>(__a, __n + 1) { 
    __stl_debug_do(_M_iter_list._Safe_init(&_M_start));
    _M_terminate_string(); 
  }

  basic_string(const _Self& __s) : _String_base<_CharT,_Alloc>(__s.get_allocator()) 
    { 
      _M_range_initialize(__s._M_start, __s._M_finish); 
    }

  basic_string(const _Self& __s, size_type __pos, size_type __n = npos,
               const __STL_ALLOC_PARAM& __a = __STL_ALLOC_INSTANCE(__STL_ALLOC_PARAM)) 
    : _String_base<_CharT,_Alloc>(__a) {
    if (__pos > __s.size())
      _M_throw_out_of_range();
    else
      _M_range_initialize(__s._M_start + __pos,
                          __s._M_start + __pos + min(__n, __s.size() - __pos));
  }

  basic_string(const _CharT* __s, size_type __n,
               const __STL_ALLOC_PARAM& __a = __STL_ALLOC_INSTANCE(__STL_ALLOC_PARAM)) 
    : _String_base<_CharT,_Alloc>(__a) 
    { 
      _M_range_initialize(__s, __s + __n); 
    }

  basic_string(const _CharT* __s,
               const __STL_ALLOC_PARAM& __a = __STL_ALLOC_INSTANCE(__STL_ALLOC_PARAM))
    : _String_base<_CharT,_Alloc>(__a) 
    {
      _M_range_initialize(__s, __s + _Traits::length(__s)); 
    }

  basic_string(size_type __n, _CharT __c,
               const __STL_ALLOC_PARAM& __a = __STL_ALLOC_INSTANCE(__STL_ALLOC_PARAM))
    : _String_base<_CharT,_Alloc>(__a, __n + 1)
  {
    __stl_debug_do(_M_iter_list._Safe_init(&_M_start));
    _M_finish = uninitialized_fill_n(_M_start, __n, __c);
    _M_terminate_string();
  }
  // Check to see if _InputIterator is an integer type.  If so, then
  // it can't be an iterator.
#ifdef __STL_MEMBER_TEMPLATES
  template <class _InputIterator>
  basic_string(_InputIterator __f, _InputIterator __l,
               const __STL_ALLOC_PARAM & __a = __STL_ALLOC_INSTANCE(__STL_ALLOC_PARAM))
    : _String_base<_CharT,_Alloc>(__a)
  {
    typedef typename _Is_integer<_InputIterator>::_Integral _Integral;
    _M_initialize_dispatch(__f, __l, _Integral());
  }
#else /* __STL_MEMBER_TEMPLATES */

# ifdef __STL_DEBUG
  basic_string(const_iterator __f, const_iterator __l)
    : _String_base<_CharT,_Alloc>(allocator_type())
  {
    _M_range_initialize(_Make_ptr(__f), _Make_ptr(__l));
  }
  basic_string(const_iterator __f, const_iterator __l,
               const __STL_ALLOC_PARAM& __a )
    : _String_base<_CharT,_Alloc>(__a)
  {
    _M_range_initialize(_Make_ptr(__f), _Make_ptr(__l));
  }
# endif

  basic_string(const _CharT* __f, const _CharT* __l,
               const __STL_ALLOC_PARAM& __a = __STL_ALLOC_INSTANCE(__STL_ALLOC_PARAM))
    : _String_base<_CharT,_Alloc>(__a)
  {
    _M_range_initialize(__f, __l);
  }

#endif

# ifdef __STL_USE_OWN_NAMESPACE
  // these conversion operations still needed for
  // strstream, etc.
  basic_string (const __std_string& __x): _String_base<_CharT,_Alloc>(allocator_type())
    {
      const char* __s = __x.c_str();
      _M_range_initialize(__s, __s + _Traits::length(__s)); 
    }
  
  operator __std_string() const { return __std_string(this->c_str()); }
# endif

  ~basic_string() { destroy(_M_start, _M_finish + 1); }
    
  _Self& operator=(const _Self& __s) {
    if (&__s != this) 
      assign(__s._M_start, __s._M_finish);
    return *this;
  }

  _Self& operator=(const _CharT* __s) 
    { return assign(__s, __s + _Traits::length(__s)); }

  _Self& operator=(_CharT __c)
    { return assign(__STATIC_CAST(size_type,1), __c); }

  static _CharT _M_null() {
#   ifndef __STL_DEFAULT_CONSTRUCTOR_BUG
    return _CharT();
#   else
    return (_CharT) 0;
#   endif
  }

private:                        // Helper functions used by constructors
                                // and elsewhere.
  // fbp : simplify integer types (char, wchar)
  void _M_construct_null_aux(_CharT* __p, __false_type) {
    construct(__p);
  }
  void _M_construct_null_aux(_CharT* __p, __true_type) {
    *__p = 0;
  }

  void _M_construct_null(_CharT* __p) {
    _M_construct_null_aux(__p, _Char_Is_Integral());
  }

private:                        
  // Helper functions used by constructors.  It is a severe error for
  // any of them to be called anywhere except from within constructors.

  void _M_terminate_string_aux(__false_type) {
    __STL_TRY {
      _M_construct_null(_M_finish);
    }
    __STL_UNWIND(destroy(_M_start, _M_finish));
  }

  void _M_terminate_string_aux(__true_type) {
    *_M_finish=0;
  }

  void _M_terminate_string() {
    _M_terminate_string_aux(_Char_Is_Integral());
  }

#ifdef __STL_MEMBER_TEMPLATES
    
  template <class _InputIter>
  void _M_range_initialize(_InputIter __f, _InputIter __l,
                           input_iterator_tag) {
    _M_allocate_block(8);
    _M_construct_null(_M_finish);
    __STL_TRY {
      append(__f, __l);
    }
    __STL_UNWIND(destroy(_M_start, _M_finish + 1));
  }

  template <class _ForwardIter>
  void _M_range_initialize(_ForwardIter __f, _ForwardIter __l, 
                           forward_iterator_tag) {
    difference_type __n = 0;
    distance(__f, __l, __n);
    _M_allocate_block(__n + 1);
    _M_finish = uninitialized_copy(__f, __l, _M_start);
    _M_terminate_string();
  }

  template <class _InputIter>
  void _M_range_initialize(_InputIter __f, _InputIter __l) {
    typedef  __STD::iterator_traits<_InputIter> _Iter_traits;
    typedef typename _Iter_traits::iterator_category _Category;
    __stl_debug_do(__check_range(__f, __l));
    _M_range_initialize(__f, __l, _Category());
    __stl_debug_do(_M_iter_list._Safe_init(&_M_start));
  }

  template <class _Integer>
  void _M_initialize_dispatch(_Integer __n, _Integer __x, __true_type) {
    _M_allocate_block(__n + 1);
    _M_finish = uninitialized_fill_n(_M_start, __n, __x);
    _M_terminate_string();
    __stl_debug_do(_M_iter_list._Safe_init(&_M_start));
  }

  template <class _InputIter>
  void _M_initialize_dispatch(_InputIter __f, _InputIter __l, __false_type) {
     _M_range_initialize(__f, __l);
  }
    
#else /* __STL_MEMBER_TEMPLATES */

  void _M_range_initialize(const _CharT* __f, const _CharT* __l) {
    __stl_debug_do(__check_range(__f, __l));
    ptrdiff_t __n = __l - __f;
    _M_allocate_block(__n + 1);
    _M_finish = uninitialized_copy(__f, __l, _M_start);
    _M_terminate_string();
    __stl_debug_do(_M_iter_list._Safe_init(&_M_start));
  }

#endif /* __STL_MEMBER_TEMPLATES */

public:                         // Iterators.
# if defined (__STL_DEBUG)
  iterator begin() { return _Make_iterator(_M_start); }
  const_iterator begin() const { return _Make_const_iterator(_M_start); }
  iterator end() { return _Make_iterator(_M_finish); }
  const_iterator end() const { return _Make_const_iterator(_M_finish); }
  void _M_deallocate_block() {
    __stl_debug_do(_M_iter_list._Invalidate_all());
    _Base::_M_deallocate_block();
  }
# else
  iterator begin()             { return _M_start; }
  iterator end()               { return _M_finish; }
  const_iterator begin() const { return _M_start; }
  const_iterator end()   const { return _M_finish; }  
# endif

  reverse_iterator rbegin()             
    { return reverse_iterator(_Make_iterator(_M_finish)); }
  reverse_iterator rend()               
    { return reverse_iterator(_Make_iterator(_M_start)); }
  const_reverse_iterator rbegin() const 
    { return const_reverse_iterator(_Make_const_iterator(_M_finish)); }
  const_reverse_iterator rend()   const 
    { return const_reverse_iterator(_Make_const_iterator(_M_start)); }

public:                         // Size, capacity, etc.
  size_type size() const { return _M_finish - _M_start; }
  size_type length() const { return size(); }

  size_t max_size() const { return _Base::max_size(); }


  void resize(size_type __n, _CharT __c) {
    if (__n <= size())
      erase(begin() + __n, end());
    else
      append(__n - size(), __c);
  }
  void resize(size_type __n) { resize(__n, _M_null()); }

  void reserve(size_type = 0);

  size_type capacity() const { return (_M_end_of_storage - _M_start) - 1; }

  void clear() {
    if (!empty()) {
      __stl_debug_do(_M_iter_list._Invalidate_all());
      _Traits::assign(*_M_start, _M_null());
      destroy(_M_start+1, _M_finish+1);
      _M_finish = _M_start;
    }
  } 

  bool empty() const { return _M_start == _M_finish; }    

public:                         // Element access.

  const_reference operator[](size_type __n) const
    { return *(_M_start + __n); }
  reference operator[](size_type __n)
    { return *(_M_start + __n); }

  const_reference at(size_type __n) const {
    if (__n >= size())
      _M_throw_out_of_range();
    return *(_M_start + __n);
  }

  reference at(size_type __n) {
    if (__n >= size())
      _M_throw_out_of_range();
    return *(_M_start + __n);
  }

public:                         // Append, operator+=, push_back.

  _Self& operator+=(const _Self& __s) { return append(__s); }
  _Self& operator+=(const _CharT* __s) { return append(__s); }
  _Self& operator+=(_CharT __c) { push_back(__c); return *this; }

  _Self& append(const _Self& __s) 
    { return append(__s._M_start, __s._M_finish); }

  _Self& append(const _Self& __s,
                       size_type __pos, size_type __n)
  {
    if (__pos > __s.size())
      _M_throw_out_of_range();
    return append(__s._M_start + __pos,
                  __s._M_start + __pos + min(__n, __s.size() - __pos));
  }

  _Self& append(const _CharT* __s, size_type __n) 
    { return append(__s, __s+__n); }

  _Self& append(const _CharT* __s) 
    { return append(__s, __s + _Traits::length(__s)); }
  _Self& append(size_type __n, _CharT __c);

#ifdef __STL_MEMBER_TEMPLATES

  // Check to see if _InputIterator is an integer type.  If so, then
  // it can't be an iterator.
  template <class _InputIter>
  _Self& append(_InputIter __first, _InputIter __last) {
    typedef typename _Is_integer<_InputIter>::_Integral _Integral;
    return _M_append_dispatch(__first, __last, _Integral());
  }

#else /* __STL_MEMBER_TEMPLATES */

  _Self& append(const _CharT* __first, const _CharT* __last);

#endif /* __STL_MEMBER_TEMPLATES */

  void push_back(_CharT __c) {
    if (_M_finish + 1 == _M_end_of_storage)
      reserve(size() + max(size(), __STATIC_CAST(size_type,1)));
    _M_construct_null(_M_finish + 1);
    _Traits::assign(*_M_finish, __c);
    ++_M_finish;
  }

  void pop_back() {
    __stl_debug_do(__invalidate_iterator(&_M_iter_list,_M_finish,iterator()));
    _Traits::assign(*(_M_finish - 1), _M_null());
    destroy(_M_finish);
    --_M_finish;
  }

private:                        // Helper functions for append.

#ifdef __STL_MEMBER_TEMPLATES

  template <class _InputIter>
  _Self& append(_InputIter __first, _InputIter __last, input_iterator_tag)
  {
	  for ( ; __first != __last ; ++__first)
	    push_back(*__first);
	  return *this;
	}

  template <class _ForwardIter>
  _Self& append(_ForwardIter __first, _ForwardIter __last, 
                       forward_iterator_tag)  {
    __stl_debug_do(__check_range(__first, __last));
    if (__first != __last) {
	    const size_type __old_size = size();
	    difference_type __n = 0;
	    distance(__first, __last, __n);
	    if (__n > max_size() || __old_size > max_size() - __n)
	      _M_throw_length_error();
	    if (__old_size + __n > capacity()) {
	      const size_type __len = __old_size +
	                            max(__old_size, __STATIC_CAST(size_type,__n)) + 1;
	      pointer __new_start = _M_allocate(__len);
	      pointer __new_finish = __new_start;
	      __STL_TRY {
	        __new_finish = uninitialized_copy(_M_start, _M_finish, __new_start);
	        __new_finish = uninitialized_copy(__first, __last, __new_finish);
	        _M_construct_null(__new_finish);
	      }
	      __STL_UNWIND((destroy(__new_start,__new_finish),
	                    _M_deallocate(__new_start,__len)));
	      destroy(_M_start, _M_finish + 1);
	      _M_deallocate_block();
	      _M_start = __new_start;
	      _M_finish = __new_finish;
	      _M_end_of_storage = __new_start + __len; 
	    }
	    else {
	      _ForwardIter __f1 = __first;
	      ++__f1;
	      uninitialized_copy(__f1, __last, _M_finish + 1);
	      __STL_TRY {
	        _M_construct_null(_M_finish + __n);
	      }
	      __STL_UNWIND(destroy(_M_finish + 1, _M_finish + __n));
	      _Traits::assign(*_M_finish, *__first);
	      _M_finish += __n;
	    }
	  }
	  return *this;  
	}

  template <class _Integer>
  _Self& _M_append_dispatch(_Integer __n, _Integer __x, __true_type) {
    return append((size_type) __n, (_CharT) __x);
  }

  template <class _InputIter>
  _Self& _M_append_dispatch(_InputIter __f, _InputIter __l,
                                   __false_type) {
    typedef typename iterator_traits<_InputIter>::iterator_category _Category;
    return append(__f, __l, _Category());
  }

#endif /* __STL_MEMBER_TEMPLATES */

public:                         // Assign
  
  _Self& assign(const _Self& __s) 
    { return assign(__s._M_start, __s._M_finish); }

  _Self& assign(const _Self& __s, 
                       size_type __pos, size_type __n) {
    if (__pos > __s.size())
      _M_throw_out_of_range();
    return assign(__s._M_start + __pos, 
                  __s._M_start + __pos + min(__n, __s.size() - __pos));
  }

  _Self& assign(const _CharT* __s, size_type __n)
    { return assign(__s, __s + __n); }

  _Self& assign(const _CharT* __s)
    { return assign(__s, __s + _Traits::length(__s)); }

  _Self& assign(size_type __n, _CharT __c);

#ifdef __STL_MEMBER_TEMPLATES

  // Check to see if _InputIterator is an integer type.  If so, then
  // it can't be an iterator.
  template <class _InputIter>
  _Self& assign(_InputIter __first, _InputIter __last) {
    typedef typename _Is_integer<_InputIter>::_Integral _Integral;
    return _M_assign_dispatch(__first, __last, _Integral());
  }

#endif  /* __STL_MEMBER_TEMPLATES */

  _Self& assign(const _CharT* __f, const _CharT* __l);

private:                        // Helper functions for assign.

#ifdef __STL_MEMBER_TEMPLATES

  template <class _Integer>
  _Self& _M_assign_dispatch(_Integer __n, _Integer __x, __true_type) {
    return assign((size_type) __n, (_CharT) __x);
  }

  template <class _InputIter>
  _Self& _M_assign_dispatch(_InputIter __f, _InputIter __l,
                                   __false_type)  {
          __stl_debug_do(__check_range(__f, __l));
          pointer __cur = _M_start;
	  while (__f != __l && __cur != _M_finish) {
	    _Traits::assign(*__cur, *__f);
	    ++__f;
	    ++__cur;
	  }
	  if (__f == __l)
	    erase(_Make_iterator(__cur), end());
	  else
	    append(__f, __l);
	  return *this;
	}

#endif  /* __STL_MEMBER_TEMPLATES */

public:                         // Insert

  _Self& insert(size_type __pos, const _Self& __s) {
    if (__pos > size())
      _M_throw_out_of_range();
    if (size() > max_size() - __s.size())
      _M_throw_length_error();
    insert(begin() + __pos, __s._M_start, __s._M_finish);
    return *this;
  }

  _Self& insert(size_type __pos, const _Self& __s,
                       size_type __beg, size_type __n) {
    if (__pos > size() || __beg > __s.size())
      _M_throw_out_of_range();
    size_type __len = min(__n, __s.size() - __beg);
    if (size() > max_size() - __len)
      _M_throw_length_error();
    insert(begin() + __pos,
           __s._M_start + __beg, __s._M_start + __beg + __len);
    return *this;
  }

  _Self& insert(size_type __pos, const _CharT* __s, size_type __n) {
    if (__pos > size())
      _M_throw_out_of_range();
    if (size() > max_size() - __n)
      _M_throw_length_error();
    insert(begin() + __pos, __s, __s + __n);
    return *this;
  }

  _Self& insert(size_type __pos, const _CharT* __s) {
    if (__pos > size())
      _M_throw_out_of_range();
    size_type __len = _Traits::length(__s);
    if (size() > max_size() - __len)
      _M_throw_length_error();
    insert(_Make_iterator(_M_start + __pos), __s, __s + __len);
    return *this;
  }
    
  _Self& insert(size_type __pos, size_type __n, _CharT __c) {
    if (__pos > size())
      _M_throw_out_of_range();
    if (size() > max_size() - __n)
      _M_throw_length_error();
    insert(begin() + __pos, __n, __c);
    return *this;
  }

  iterator insert(iterator __p, _CharT __c) {
    if (__p == end()) {
      push_back(__c);
      return _Make_iterator(_M_finish - 1);
    }
    else
      return _Make_iterator(_M_insert_aux(_Make_ptr(__p), __c));
  }

  void insert(iterator __p, size_t __n, _CharT __c);

#ifdef __STL_MEMBER_TEMPLATES

  // Check to see if _InputIterator is an integer type.  If so, then
  // it can't be an iterator.
  template <class _InputIter>
  void insert(iterator __p, _InputIter __first, _InputIter __last) {
    typedef typename _Is_integer<_InputIter>::_Integral _Integral;
    _M_insert_dispatch(__p, __first, __last, _Integral());
  }

#else /* __STL_MEMBER_TEMPLATES */

  void insert(iterator __p, const _CharT* __first, const _CharT* __last);
# ifdef __STL_DEBUG
  void insert(iterator __p, const_iterator __first, const_iterator __last) {
    insert(__p, __first._Get_iterator(), __last._Get_iterator()); 
  }
# endif
#endif /* __STL_MEMBER_TEMPLATES */

private:                        // Helper functions for insert.

#ifdef __STL_MEMBER_TEMPLATES

  template <class _InputIter>
  void insert(iterator __p, _InputIter __first, _InputIter __last,
	      input_iterator_tag)
  {
	  for ( ; __first != __last; ++__first) {
	    __p = insert(__p, *__first);
	    ++__p;
	  }
	}

  template <class _ForwardIter>
  void insert(iterator __position, _ForwardIter __first, _ForwardIter __last, 
	      forward_iterator_tag)  {
    __stl_debug_do(__check_range(__first,__last));
    if (__first != __last) {
      difference_type __n = 0;
      distance(__first, __last, __n);
      if (_M_end_of_storage - _M_finish >= __n + 1) {
	const difference_type __elems_after = _M_finish - _Make_ptr(__position);
	pointer __old_finish = _M_finish;
	if (__elems_after >= __n) {
	  uninitialized_copy((_M_finish - __n) + 1, _M_finish + 1,
			     _M_finish + 1);
	  _M_finish += __n;
	  _Traits::move(_Make_ptr(__position) + __n,
			_Make_ptr(__position), (__elems_after - __n) + 1);
	  _M_copy(__first, __last, _Make_ptr(__position));
	      }
	else {
	  _ForwardIter __mid = __first;
	  advance(__mid, __elems_after + 1);
	  uninitialized_copy(__mid, __last, _M_finish + 1);
	  _M_finish += __n - __elems_after;
	        __STL_TRY {
	          uninitialized_copy(_Make_ptr(__position), __old_finish + 1, _M_finish);
	          _M_finish += __elems_after;
	        }
	        __STL_UNWIND((destroy(__old_finish + 1, _M_finish), 
	                      _M_finish = __old_finish));
	        _M_copy(__first, __mid, _Make_ptr(__position));
	}
      }
      else {
	const size_type __old_size = size();        
	const size_type __len
	  = __old_size + max(__old_size, __STATIC_CAST(size_type,__n)) + 1;
	      pointer __new_start = _M_allocate(__len);
	      pointer __new_finish = __new_start;
	      __STL_TRY {
	        __new_finish = uninitialized_copy(_M_start, _Make_ptr(__position), __new_start);
	        __new_finish = uninitialized_copy(__first, __last, __new_finish);
	        __new_finish
	          = uninitialized_copy(_Make_ptr(__position), _M_finish, __new_finish);
	        _M_construct_null(__new_finish);
	      }
	      __STL_UNWIND((destroy(__new_start,__new_finish),
	                    _M_deallocate(__new_start,__len)));
	      destroy(_M_start, _M_finish + 1);
	      _M_deallocate_block();
	      _M_start = __new_start;
	      _M_finish = __new_finish;
	      _M_end_of_storage = __new_start + __len; 
	    }
    }
  }
  

  template <class _Integer>
  void _M_insert_dispatch(iterator __p, _Integer __n, _Integer __x,
                          __true_type) {
    insert(__p, (size_type) __n, (_CharT) __x);
  }

  template <class _InputIter>
  void _M_insert_dispatch(iterator __p, _InputIter __first, _InputIter __last,
                          __false_type) {
    typedef typename iterator_traits<_InputIter>::iterator_category _Category;
    __stl_debug_do(__check_range(__first, __last));
    insert(__p, __first, __last, _Category());
  }

  template <class _InputIterator>
  void 
  _M_copy(_InputIterator __first, _InputIterator __last, pointer __result) {
    __stl_debug_do(__check_range(__first, __last));
    for ( ; __first != __last; ++__first, ++__result)
      _Traits::assign(*__result, *__first);
  }

#endif /* __STL_MEMBER_TEMPLATES */

  pointer _M_insert_aux(pointer, _CharT);

  void 
  _M_copy(const _CharT* __first, const _CharT* __last, _CharT* __result) {
    __stl_debug_do(__check_range(__first, __last));
    _Traits::copy(__result, __first, __last - __first);
  }

public:                         // Erase.

  _Self& erase(size_type __pos = 0, size_type __n = npos) {
    if (__pos > size())
      _M_throw_out_of_range();
    erase(begin() + __pos, begin() + __pos + min(__n, size() - __pos));
    return *this;
  }  

  iterator erase(iterator __position) {
    __stl_debug_do(__check_if_owner(&_M_iter_list, __position));
                                // The move includes the terminating _CharT().
    _Traits::move(_Make_ptr(__position), _Make_ptr(__position) + 1, _M_finish - _Make_ptr(__position));
    __stl_debug_do(__invalidate_iterator(&_M_iter_list,_M_finish,iterator()));
    destroy(_M_finish);
    --_M_finish;
    return __position;
  }

  iterator erase(iterator __first, iterator __last) {
    __stl_debug_do(__check_range(__first, __last)&&__check_if_owner(&_M_iter_list,__first));
    if (__first != __last) {
                                // The move includes the terminating _CharT().
      _Traits::move(_Make_ptr(__first), _Make_ptr(__last), (_M_finish - _Make_ptr(__last)) + 1);
      pointer __new_finish = _M_finish - (__last - __first);
      destroy(__new_finish + 1, _M_finish + 1);
      __stl_debug_do(__invalidate_range(&_M_iter_list, _Make_iterator(__new_finish+1), end()));
      _M_finish = __new_finish;
    }
    return __first;
  }

public:                         // Replace.  (Conceptually equivalent
                                // to erase followed by insert.)
  _Self& replace(size_type __pos, size_type __n, 
                        const _Self& __s) {
    if (__pos > size())
      _M_throw_out_of_range();
    const size_type __len = min(__n, size() - __pos);
    if (size() - __len >= max_size() - __s.size())
      _M_throw_length_error();
    return replace(begin() + __pos, begin() + __pos + __len, 
                   __s._M_start, __s._M_finish);
  }

  _Self& replace(size_type __pos1, size_type __n1,
                        const _Self& __s,
                        size_type __pos2, size_type __n2) {
    if (__pos1 > size() || __pos2 > __s.size())
      _M_throw_out_of_range();
    const size_type __len1 = min(__n1, size() - __pos1);
    const size_type __len2 = min(__n2, __s.size() - __pos2);
    if (size() - __len1 >= max_size() - __len2)
      _M_throw_length_error();
    return replace(begin() + __pos1, begin() + __pos1 + __len1,
                   __s._M_start + __pos2, __s._M_start + __pos2 + __len2);
  }

  _Self& replace(size_type __pos, size_type __n1,
                        const _CharT* __s, size_type __n2) {
    if (__pos > size())
      _M_throw_out_of_range();
    const size_type __len = min(__n1, size() - __pos);
    if (__n2 > max_size() || size() - __len >= max_size() - __n2)
      _M_throw_length_error();
    return replace(begin() + __pos, begin() + __pos + __len,
                   __s, __s + __n2);
  }

  _Self& replace(size_type __pos, size_type __n1,
                        const _CharT* __s) {
    if (__pos > size())
      _M_throw_out_of_range();
    const size_type __len = min(__n1, size() - __pos);
    const size_type __n2 = _Traits::length(__s);
    if (__n2 > max_size() || size() - __len >= max_size() - __n2)
      _M_throw_length_error();
    return replace(begin() + __pos, begin() + __pos + __len,
                   __s, __s + _Traits::length(__s));
  }

  _Self& replace(size_type __pos, size_type __n1,
                        size_type __n2, _CharT __c) {
    if (__pos > size())
      _M_throw_out_of_range();
    const size_type __len = min(__n1, size() - __pos);
    if (__n2 > max_size() || size() - __len >= max_size() - __n2)
      _M_throw_length_error();
    return replace(begin() + __pos, begin() + __pos + __len, __n2, __c);
  }

  _Self& replace(iterator __first, iterator __last, 
                        const _Self& __s) 
    { return replace(__first, __last, __s._M_start, __s._M_finish); }

  _Self& replace(iterator __first, iterator __last,
                        const _CharT* __s, size_type __n) 
    { return replace(__first, __last, __s, __s + __n); }

  _Self& replace(iterator __first, iterator __last,
                        const _CharT* __s) {
    return replace(__first, __last, __s, __s + _Traits::length(__s));
  }

  _Self& replace(iterator __first, iterator __last, 
                        size_type __n, _CharT __c);

  // Check to see if _InputIterator is an integer type.  If so, then
  // it can't be an iterator.
#ifdef __STL_MEMBER_TEMPLATES
  template <class _InputIter>
  _Self& replace(iterator __first, iterator __last,
                        _InputIter __f, _InputIter __l) {
    typedef typename _Is_integer<_InputIter>::_Integral _Integral;
    return _M_replace_dispatch(__first, __last, __f, __l,  _Integral());
  }
#else /* __STL_MEMBER_TEMPLATES */
  _Self& replace(iterator __first, iterator __last,
		 const _CharT* __f, const _CharT* __l);
#endif /* __STL_MEMBER_TEMPLATES */

private:                        // Helper functions for replace.

#ifdef __STL_MEMBER_TEMPLATES

  template <class _Integer>
  _Self& _M_replace_dispatch(iterator __first, iterator __last,
                                    _Integer __n, _Integer __x,
                                    __true_type) {
    return replace(__first, __last, (size_type) __n, (_CharT) __x);
  }

  template <class _InputIter>
  _Self& _M_replace_dispatch(iterator __first, iterator __last,
                                    _InputIter __f, _InputIter __l,
                                    __false_type) {
    typedef typename iterator_traits<_InputIter>::iterator_category _Category;
    __stl_debug_do(__check_if_owner(__first) && __check_range(__first, __last) 
		   && __check_range(__f, __l));
    return replace(__first, __last, __f, __l, _Category());
  }

  template <class _InputIter>
  _Self& replace(iterator __first, iterator __last,
                        _InputIter __f, _InputIter __l, input_iterator_tag)  {
	  for ( ; __first != __last && __f != __l; ++__first, ++__f)
	    _Traits::assign(*__first, *__f);

	  if (__f == __l)
	    erase(__first, __last);
	  else
	    insert(__last, __f, __l);
	  return *this;
	}

  template <class _ForwardIter>
  _Self& replace(iterator __first, iterator __last,
                        _ForwardIter __f, _ForwardIter __l, 
                        forward_iterator_tag)  {
	  difference_type __n = 0;
	  distance(__f, __l, __n);
	  const difference_type __len = __last - __first;
	  if (__len >= __n) {
	    _M_copy(__f, __l, __first);
	    erase(__first + __n, __last);
	  }
	  else {
	    _ForwardIter __m = __f;
	    advance(__m, __len);
	    _M_copy(__f, __m, __first);
	    insert(__last, __m, __l);
	  }
	  return *this;
	}

#endif /* __STL_MEMBER_TEMPLATES */

public:                         // Other modifier member functions.

  size_type copy(_CharT* __s, size_type __n, size_type __pos = 0) const {
    if (__pos > size())
      _M_throw_out_of_range();
    const size_type __len = min(__n, size() - __pos);
    _Traits::copy(__s, _M_start + __pos, __len);
    return __len;
  }

  void swap(_Self& __s) {
    __stl_debug_do(_M_iter_list._Swap_owners(__s._M_iter_list));
    __STD::swap(_M_start, __s._M_start);
    __STD::swap(_M_finish, __s._M_finish);
    __STD::swap(_M_end_of_storage, __s._M_end_of_storage);
  }

public:                         // Conversion to C string.

  const _CharT* c_str() const { return _M_start; }
  const _CharT* data()  const { return _M_start; }

public:                         // find.

  size_type find(const _Self& __s, size_type __pos = 0) const 
    { return find(__s._M_start, __pos, __s.size()); }

  size_type find(const _CharT* __s, size_type __pos = 0) const 
    { return find(__s, __pos, _Traits::length(__s)); }

  size_type find(const _CharT* __s, size_type __pos, size_type __n) const;
  size_type find(_CharT __c, size_type __pos = 0) const;

public:                         // rfind.

  size_type rfind(const _Self& __s, size_type __pos = npos) const 
    { return rfind(__s._M_start, __pos, __s.size()); }

  size_type rfind(const _CharT* __s, size_type __pos = npos) const 
    { return rfind(__s, __pos, _Traits::length(__s)); }

  size_type rfind(const _CharT* __s, size_type __pos, size_type __n) const;
  size_type rfind(_CharT __c, size_type __pos = npos) const;

public:                         // find_first_of
  
  size_type find_first_of(const _Self& __s, size_type __pos = 0) const 
    { return find_first_of(__s._M_start, __pos, __s.size()); }

  size_type find_first_of(const _CharT* __s, size_type __pos = 0) const 
    { return find_first_of(__s, __pos, _Traits::length(__s)); }

  size_type find_first_of(const _CharT* __s, size_type __pos, 
                          size_type __n) const;

  size_type find_first_of(_CharT __c, size_type __pos = 0) const 
    { return find(__c, __pos); }

public:                         // find_last_of

  size_type find_last_of(const _Self& __s,
                         size_type __pos = npos) const
    { return find_last_of(__s._M_start, __pos, __s.size()); }

  size_type find_last_of(const _CharT* __s, size_type __pos = npos) const 
    { return find_last_of(__s, __pos, _Traits::length(__s)); }

  size_type find_last_of(const _CharT* __s, size_type __pos, 
                         size_type __n) const;

  size_type find_last_of(_CharT __c, size_type __pos = npos) const {
    return rfind(__c, __pos);
  }

public:                         // find_first_not_of

  size_type find_first_not_of(const _Self& __s, 
                              size_type __pos = 0) const 
    { return find_first_not_of(__s._M_start, __pos, __s.size()); }

  size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const 
    { return find_first_not_of(__s, __pos, _Traits::length(__s)); }

  size_type find_first_not_of(const _CharT* __s, size_type __pos,
                              size_type __n) const;

  size_type find_first_not_of(_CharT __c, size_type __pos = 0) const;

public:                         // find_last_not_of

  size_type find_last_not_of(const _Self& __s, 
                             size_type __pos = npos) const
    { return find_last_not_of(__s._M_start, __pos, __s.size()); }

  size_type find_last_not_of(const _CharT* __s, size_type __pos = npos) const
    { return find_last_not_of(__s, __pos, _Traits::length(__s)); }

  size_type find_last_not_of(const _CharT* __s, size_type __pos,
                             size_type __n) const;

  size_type find_last_not_of(_CharT __c, size_type __pos = npos) const;

public:                         // Substring.

  _Self substr(size_type __pos = 0, size_type __n = npos) const {
    if (__pos > size())
      _M_throw_out_of_range();
    return _Self(_M_start + __pos, 
                        _M_start + __pos + min(__n, size() - __pos));
  }

public:                         // Compare

  int compare(const _Self& __s) const 
    { return _M_compare(_M_start, _M_finish, __s._M_start, __s._M_finish); }

  int compare(size_type __pos1, size_type __n1,
              const _Self& __s) const {
    if (__pos1 > size())
      _M_throw_out_of_range();
    return _M_compare(_M_start + __pos1, 
                      _M_start + __pos1 + min(__n1, size() - __pos1),
                      __s._M_start, __s._M_finish);
  }
    
  int compare(size_type __pos1, size_type __n1,
              const _Self& __s,
              size_type __pos2, size_type __n2) const {
    if (__pos1 > size() || __pos2 > __s.size())
      _M_throw_out_of_range();
    return _M_compare(_M_start + __pos1, 
                      _M_start + __pos1 + min(__n1, size() - __pos1),
                      __s._M_start + __pos2, 
                      __s._M_start + __pos2 + min(__n2, size() - __pos2));
  }

  int compare(const _CharT* __s) const {
    return _M_compare(_M_start, _M_finish, __s, __s + _Traits::length(__s));
  }

  int compare(size_type __pos1, size_type __n1, const _CharT* __s) const {
    if (__pos1 > size())
      _M_throw_out_of_range();
    return _M_compare(_M_start + __pos1, 
                      _M_start + __pos1 + min(__n1, size() - __pos1),
                      __s, __s + _Traits::length(__s));
  }

  int compare(size_type __pos1, size_type __n1, const _CharT* __s,
              size_type __n2) const {
    if (__pos1 > size())
      _M_throw_out_of_range();
    return _M_compare(_M_start + __pos1, 
                      _M_start + __pos1 + min(__n1, size() - __pos1),
                      __s, __s + __n2);
  }

public:                        // Helper functions for compare.
  
  static int _M_compare(const _CharT* __f1, const _CharT* __l1,
                        const _CharT* __f2, const _CharT* __l2) {
    const ptrdiff_t __n1 = __l1 - __f1;
    const ptrdiff_t __n2 = __l2 - __f2;
    const int cmp = _Traits::compare(__f1, __f2, min(__n1, __n2));
    return cmp != 0 ? cmp : (__n1 < __n2 ? -1 : (__n1 > __n2 ? 1 : 0));
  }
};


# if defined (__STL_NESTED_TYPE_PARAM_BUG)
#  define __size_type__ size_t
#  define size_type size_t
#  if defined (__STL_DEBUG)
#   define __iterator__       _String_iterator<_CharT,_CharT&, _CharT*>
// #   define __const_iterator__ _String_iterator<_CharT, const _CharT&, const _CharT*>
#  else
#   define __iterator__  _CharT*
#  endif
#   define iterator      __iterator__
# else
#  define __size_type__ __STL_TYPENAME_ON_RETURN_TYPE basic_string<_CharT,_Traits,_Alloc>::size_type
#  define __iterator__  __STL_TYPENAME_ON_RETURN_TYPE basic_string<_CharT,_Traits,_Alloc>::iterator
# endif

// ------------------------------------------------------------
// Non-inline declarations.

# if (__STL_STATIC_TEMPLATE_DATA > 0)
template <class _CharT, class _Traits, class _Alloc> 
const __size_type__
basic_string<_CharT,_Traits,_Alloc>::npos = -1;
# else /* __STL_STATIC_TEMPLATE_DATA */
template class basic_string<char,char_traits<char>,allocator<char> >;
const size_t string::npos __STL_WEAK = (size_t)-1;
#  ifdef __STL_WCHAR_T
template class basic_string<wchar_t,char_traits<wchar_t>,allocator<wchar_t> >;
const size_t wstring::npos __STL_WEAK = (size_t)-1;
#  endif
# endif /* __STL_STATIC_TEMPLATE_DATA */

// _String_base methods
template <class _Tp, class _Alloc> 
void _String_base<_Tp,_Alloc>::_M_throw_length_error() const {
  __STL_THROW(length_error(string("basic_string")));
}

template <class _Tp, class _Alloc> 
void _String_base<_Tp, _Alloc>::_M_throw_out_of_range() const {
  __STL_THROW(out_of_range(string("basic_string")));
}

// Change the string's capacity so that it is large enough to hold
//  at least __res_arg elements, plus the terminating _CharT().  Note that,
//  if __res_arg < capacity(), this member function may actually decrease
//  the string's capacity.
template <class _CharT, class _Traits, class _Alloc> 
void basic_string<_CharT,_Traits,_Alloc>::reserve(__size_type__ __res_arg) {
  if (__res_arg > max_size())
    _M_throw_length_error();

  size_type __n = max(__res_arg, size()) + 1;
  pointer __new_start = _M_allocate(__n);
  pointer __new_finish = __new_start;

  __STL_TRY {
    __new_finish = uninitialized_copy(_M_start, _M_finish, __new_start);
    _M_construct_null(__new_finish);
  }
  __STL_UNWIND((destroy(__new_start, __new_finish), 
                _M_deallocate(__new_start, __n)));

  destroy(_M_start, _M_finish + 1);
  _M_deallocate_block();
  _M_start = __new_start;
  _M_finish = __new_finish;
  _M_end_of_storage = __new_start + __n;
}

template <class _CharT, class _Traits, class _Alloc> 
basic_string<_CharT,_Traits,_Alloc>& 
basic_string<_CharT,_Traits,_Alloc>::append(__size_type__ __n, _CharT __c) {
  if (__n > max_size() || size() > max_size() - __n)
    _M_throw_length_error();
  if (size() + __n > capacity())
    reserve(size() + max(size(), __n));
  if (__n > 0) {
    uninitialized_fill_n(_M_finish + 1, __n - 1, __c);
    __STL_TRY {
      _M_construct_null(_M_finish + __n);
    }
    __STL_UNWIND(destroy(_M_finish + 1, _M_finish + __n));
    _Traits::assign(*_M_finish, __c);
    _M_finish += __n;
  }
  return *this;
}

#ifndef __STL_MEMBER_TEMPLATES

template <class _Tp, class _Traits, class _Alloc> 
basic_string<_Tp, _Traits, _Alloc>& 
basic_string<_Tp, _Traits, _Alloc>::append(const _Tp* __first,
                                           const _Tp* __last)
{
  if (__first != __last) {
    const size_type __old_size = size();
    ptrdiff_t __n = __last - __first;
    if ((size_type)__n > max_size() || __old_size > max_size() - __n)
      _M_throw_length_error();
    if (__old_size + __n > capacity()) {
      const size_type __len = __old_size + max(__old_size, (size_t) __n) + 1;
      pointer __new_start = _M_allocate(__len);
      pointer __new_finish = __new_start;
      __STL_TRY {
        __new_finish = uninitialized_copy(_M_start, _M_finish, __new_start);
        __new_finish = uninitialized_copy(__first, __last, __new_finish);
        _M_construct_null(__new_finish);
      }
      __STL_UNWIND((destroy(__new_start,__new_finish),
                    _M_deallocate(__new_start,__len)));
      destroy(_M_start, _M_finish + 1);
      _M_deallocate_block();
      _M_start = __new_start;
      _M_finish = __new_finish;
      _M_end_of_storage = __new_start + __len; 
    }
    else {
      const _Tp* __f1 = __first;
      ++__f1;
      uninitialized_copy(__f1, __last, _M_finish + 1);
      __STL_TRY {
        _M_construct_null(_M_finish + __n);
      }
      __STL_UNWIND(destroy(_M_finish + 1, _M_finish + __n));
      _Traits::assign(*_M_finish, *__first);
      _M_finish += __n;
    }
  }
  return *this;  
}

#endif /* __STL_MEMBER_TEMPLATES */

template <class _CharT, class _Traits, class _Alloc> 
basic_string<_CharT,_Traits,_Alloc>& 
basic_string<_CharT,_Traits,_Alloc>::assign(__size_type__ __n, _CharT __c) {
  if (__n <= size()) {
    _Traits::assign(_M_start, __n, __c);
    erase(begin() + __n, end());
  }
  else {
    _Traits::assign(_M_start, size(), __c);
    append(__n - size(), __c);
  }
  return *this;
}

template <class _CharT, class _Traits, class _Alloc> 
basic_string<_CharT,_Traits,_Alloc>& 
basic_string<_CharT,_Traits,_Alloc>::assign(const _CharT* __f, 
                                            const _CharT* __l)
{
  __stl_debug_do(__check_range(__f, __l));
  const ptrdiff_t __n = __l - __f;
  if (__n <= size()) {
    _Traits::copy(_M_start, __f, __n);
    erase(begin() + __n, end());
  }
  else {
    _Traits::copy(_M_start, __f, size());
    append(__f + size(), __l);
  }
  return *this;
}

template <class _CharT, class _Traits, class _Alloc>
_CharT* 
basic_string<_CharT,_Traits,_Alloc>
  ::_M_insert_aux(_CharT* __p,
                  _CharT __c)
{
  pointer __new_pos = __p;
  if (_M_finish + 1 < _M_end_of_storage) {
    _M_construct_null(_M_finish + 1);
    _Traits::move(__p + 1, __p, _M_finish - __p);
    _Traits::assign(*__p, __c);
    ++_M_finish;
  }
  else {
    const size_type __old_len = size();
    const size_type __len = __old_len +
                            max(__old_len, __STATIC_CAST(size_type,1)) + 1;
    pointer __new_start = _M_allocate(__len);
    pointer __new_finish = __new_start;
    __STL_TRY {
      __new_pos = uninitialized_copy(_M_start, __p, __new_start);
      construct(__new_pos, __c);
      __new_finish = __new_pos + 1;
      __new_finish = uninitialized_copy(__p, _M_finish, __new_finish);
      _M_construct_null(__new_finish);
    }
    __STL_UNWIND((destroy(__new_start,__new_finish), 
                  _M_deallocate(__new_start,__len)));
    destroy(_M_start, _M_finish + 1);
    _M_deallocate_block();
    _M_start = __new_start;
    _M_finish = __new_finish;
    _M_end_of_storage = __new_start + __len;
  }
  return __new_pos;
}

template <class _CharT, class _Traits, class _Alloc>
void basic_string<_CharT,_Traits,_Alloc>::insert(__iterator__ __position,
           size_t __n, _CharT __c)
{
  __stl_debug_do(__check_if_owner(&_M_iter_list,__position));
  if (__n != 0) {
    if (size_type(_M_end_of_storage - _M_finish) >= __n + 1) {
      const size_type __elems_after = _M_finish - _Make_ptr(__position);
      pointer __old_finish = _M_finish;
      if (__elems_after >= __n) {
        uninitialized_copy((_M_finish - __n) + 1, _M_finish + 1,
                           _M_finish + 1);
        _M_finish += __n;
        _Traits::move(_Make_ptr(__position) + __n,
                      _Make_ptr(__position), (__elems_after - __n) + 1);
        _Traits::assign(_Make_ptr(__position), __n, __c);
      }
      else {
        uninitialized_fill_n(_M_finish + 1, __n - __elems_after - 1, __c);
        _M_finish += __n - __elems_after;
        __STL_TRY {
          uninitialized_copy(_Make_ptr(__position), __old_finish + 1, _M_finish);
          _M_finish += __elems_after;
        }
        __STL_UNWIND((destroy(__old_finish + 1, _M_finish), 
                      _M_finish = __old_finish));
        _Traits::assign(_Make_ptr(__position), __elems_after + 1, __c);
      }
    }
    else {
      const size_type __old_size = size();        
      const size_type __len = __old_size + max(__old_size, __n) + 1;
      pointer __new_start = _M_allocate(__len);
      pointer __new_finish = __new_start;
      __STL_TRY {
        __new_finish = uninitialized_copy(_M_start, _Make_ptr(__position), __new_start);
        __new_finish = uninitialized_fill_n(__new_finish, __n, __c);
        __new_finish = uninitialized_copy(_Make_ptr(__position), _M_finish,
                                          __new_finish);
        _M_construct_null(__new_finish);
      }
      __STL_UNWIND((destroy(__new_start,__new_finish),
                    _M_deallocate(__new_start,__len)));
      destroy(_M_start, _M_finish + 1);
      _M_deallocate_block();
      _M_start = __new_start;
      _M_finish = __new_finish;
      _M_end_of_storage = __new_start + __len;    
    }
  }
}

#ifndef __STL_MEMBER_TEMPLATES

template <class _CharT, class _Traits, class _Alloc>
void 
basic_string<_CharT,_Traits,_Alloc>::insert(__iterator__ __position,
                                            const _CharT* __first, 
                                            const _CharT* __last)
{
  __stl_debug_do(__check_if_owner(&_M_iter_list,__position) && 
		 __check_range(__first, __last));
  if (__first != __last) {
    const ptrdiff_t __n = __last - __first;
    if (_M_end_of_storage - _M_finish >= __n + 1) {
      const ptrdiff_t __elems_after = _M_finish - _Make_ptr(__position);
      pointer __old_finish = _M_finish;
      if (__elems_after >= __n) {
        uninitialized_copy((_M_finish - __n) + 1, _M_finish + 1,
                           _M_finish + 1);
        _M_finish += __n;
        _Traits::move(_Make_ptr(__position) + __n,
                      _Make_ptr(__position), (__elems_after - __n) + 1);
        _M_copy(__first, __last, _Make_ptr(__position));
      }
      else {
        const _CharT* __mid = __first;
        advance(__mid, __elems_after + 1);
        uninitialized_copy(__mid, __last, _M_finish + 1);
        _M_finish += __n - __elems_after;
        __STL_TRY {
          uninitialized_copy(_Make_ptr(__position), __old_finish + 1, _M_finish);
          _M_finish += __elems_after;
        }
        __STL_UNWIND((destroy(__old_finish + 1, _M_finish), 
                      _M_finish = __old_finish));
        _M_copy(__first, __mid, _Make_ptr(__position));
      }
    }
    else {
      const size_type __old_size = size();        
      const size_type __len
        = __old_size + max(__old_size, __STATIC_CAST(const size_type,__n)) + 1;
      pointer __new_start = _M_allocate(__len);
      pointer __new_finish = __new_start;
      __STL_TRY {
        __new_finish = uninitialized_copy(_M_start, _Make_ptr(__position), __new_start);
        __new_finish = uninitialized_copy(__first, __last, __new_finish);
        __new_finish
          = uninitialized_copy(_Make_ptr(__position), _M_finish, __new_finish);
        _M_construct_null(__new_finish);
      }
      __STL_UNWIND((destroy(__new_start,__new_finish),
                    _M_deallocate(__new_start,__len)));
      destroy(_M_start, _M_finish + 1);
      _M_deallocate_block();
      _M_start = __new_start;
      _M_finish = __new_finish;
      _M_end_of_storage = __new_start + __len; 
    }
  }
}

#endif /* __STL_MEMBER_TEMPLATES */

template <class _CharT, class _Traits, class _Alloc>
basic_string<_CharT,_Traits,_Alloc>&
basic_string<_CharT,_Traits,_Alloc>
  ::replace(iterator __first, iterator __last, __size_type__ __n, _CharT __c)
{
  __stl_debug_do(__check_if_owner(&_M_iter_list,__first) 
		 && __check_range(__first, __last));
  const size_type __len = __STATIC_CAST(size_type,(__last - __first));
  if (__len >= __n) {
    _Traits::assign(_Make_ptr(__first), __n, __c);
    erase(__first + __n, __last);
  }
  else {
    _Traits::assign(_Make_ptr(__first), __len, __c);
    insert(__last, __n - __len, __c);
  }
  return *this;
}

#ifndef __STL_MEMBER_TEMPLATES


template <class _CharT, class _Traits, class _Alloc>
basic_string<_CharT,_Traits,_Alloc>&
basic_string<_CharT,_Traits,_Alloc>
  ::replace(iterator __first, iterator __last,
            const _CharT* __f, const _CharT* __l)
{
  __stl_debug_do(__check_if_owner(&_M_iter_list,__first) && 
		 __check_range(__first, __last) &&
		 __check_range(__f, __l));
  const ptrdiff_t         __n = __l - __f;
  const difference_type __len = __last - __first;
  if (__len >= __n) {
    _M_copy(__f, __l, _Make_ptr(__first));
    erase(__first + __n, __last);
  }
  else {
    const _CharT* __m = __f + __len;
    _M_copy(__f, __m, _Make_ptr(__first));
    insert(__last, __m, __l);
  }
  return *this;
}

#endif /* __STL_MEMBER_TEMPLATES */

template <class _CharT, class _Traits, class _Alloc>
__size_type__
basic_string<_CharT,_Traits,_Alloc>
  ::find(const _CharT* __s, size_type __pos, size_type __n) const 
{
  if (__pos >= size())
    return npos;
  else {
    const const_pointer __result =
      search((const _CharT*)_M_start + __pos, (const _CharT*)_M_finish, 
             __s, __s + __n, _Eq_traits<_Traits>());
    return __result != _M_finish ? __result - _M_start : npos;
  }
}

template <class _CharT, class _Traits, class _Alloc>
__size_type__
basic_string<_CharT,_Traits,_Alloc>
  ::find(_CharT __c, size_type __pos) const 
{
  if (__pos >= size())
    return npos;
  else {
    const const_pointer __result =
      find_if((const _CharT*)_M_start + __pos, (const _CharT*)_M_finish,
              bind2nd(_Eq_traits<_Traits>(), __c));
    return __result != _M_finish ? __result - _M_start : npos;
  }
}    

template <class _CharT, class _Traits, class _Alloc>
__size_type__
basic_string<_CharT,_Traits,_Alloc>
  ::rfind(const _CharT* __s, size_type __pos, size_type __n) const 
{
  const size_t __len = size();

  if (__n > __len)
    return npos;
  else if (__n == 0)
    return min(__len, __pos);
  else {
    const_pointer __last = _M_start + min(__len - __n, __pos) + __n;
    const_pointer __result = find_end((const_pointer)_M_start, __last,
				      __s, __s + __n,
				      _Eq_traits<_Traits>());
    return __result != __last ? __result - _M_start : npos;
  }
}

template <class _CharT, class _Traits, class _Alloc>
__size_type__
basic_string<_CharT,_Traits,_Alloc>
  ::rfind(_CharT __c, size_type __pos) const 
{
  const size_type __len = size();

  if (__len < 1)
    return npos;
  else {
    const const_iterator __last = begin() + min(__len - 1, __pos) + 1;
    const_reverse_iterator __rresult =
      find_if(const_reverse_iterator(__last), rend(),
              bind2nd(_Eq_traits<_Traits>(), __c));
    return __rresult != rend() ? (__rresult.base() - 1) - begin() : npos;
  }
}

template <class _CharT, class _Traits, class _Alloc>
__size_type__
basic_string<_CharT,_Traits,_Alloc>
  ::find_first_of(const _CharT* __s, size_type __pos, size_type __n) const
{
  if (__pos >= size())
    return npos;
  else {
    const_iterator __result = __STD::find_first_of(begin() + __pos, end(),
                                                   __s, __s + __n,
                                                   _Eq_traits<_Traits>());
    return __result != end() ? __result - begin() : npos;
  }
}


template <class _CharT, class _Traits, class _Alloc>
__size_type__
basic_string<_CharT,_Traits,_Alloc>
  ::find_last_of(const _CharT* __s, size_type __pos, size_type __n) const
{
  const size_type __len = size();

  if (__len < 1)
    return npos;
  else {
    const const_iterator __last = begin() + min(__len - 1, __pos) + 1;
    const const_reverse_iterator __rresult =
      __STD::find_first_of(const_reverse_iterator(__last), rend(),
                           __s, __s + __n,
                           _Eq_traits<_Traits>());
    return __rresult != rend() ? (__rresult.base() - 1) - begin() : npos;
  }
}


template <class _CharT, class _Traits, class _Alloc>
__size_type__
basic_string<_CharT,_Traits,_Alloc>
  ::find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const
{
  typedef typename _Traits::char_type _CharType;
  if (__pos > size())
    return npos;
  else {
    const_pointer __result = find_if((const _CharT*)_M_start + __pos, 
				      (const _CharT*)_M_finish,
                                _Not_within_traits<_Traits>((const _CharType*)__s, 
							    (const _CharType*)__s + __n));
    return __result != _M_finish ? __result - _M_start : npos;
  }
}

template <class _CharT, class _Traits, class _Alloc>
__size_type__
basic_string<_CharT,_Traits,_Alloc>
  ::find_first_not_of(_CharT __c, size_type __pos) const
{
  if (__pos > size())
    return npos;
  else {
    const_pointer __result = find_if((const _CharT*)_M_start + __pos, (const _CharT*)_M_finish,
				     not1(bind2nd(_Eq_traits<_Traits>(), __c)));
    return __result != _M_finish ? __result - _M_start : npos;
  }
}    

template <class _CharT, class _Traits, class _Alloc>
__size_type__
basic_string<_CharT,_Traits,_Alloc>
  ::find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const 
{
  typedef typename _Traits::char_type _CharType;
  const size_type __len = size();

  if (__len < 1)
    return npos;
  else {
    const_iterator __last = begin() + min(__len - 1, __pos) + 1;
    const_reverse_iterator __rlast = const_reverse_iterator(__last);
    const_reverse_iterator __rresult =
      find_if(__rlast, rend(),
              _Not_within_traits<_Traits>((const _CharType*)__s, 
					  (const _CharType*)__s + __n));
    return __rresult != rend() ? (__rresult.base() - 1) - begin() : npos;
  }
}

template <class _CharT, class _Traits, class _Alloc>
__size_type__
basic_string<_CharT, _Traits, _Alloc>
  ::find_last_not_of(_CharT __c, size_type __pos) const 
{
  const size_type __len = size();

  if (__len < 1)
    return npos;
  else {
    const_iterator __last = begin() + min(__len - 1, __pos) + 1;
    const_reverse_iterator __rlast = const_reverse_iterator(__last);
    const_reverse_iterator __rresult =
      find_if(__rlast, rend(),
              not1(bind2nd(_Eq_traits<_Traits>(), __c)));
    return __rresult != rend() ? (__rresult.base() - 1) - begin() : npos;
  }
}

// ------------------------------------------------------------
// Non-member functions.

template <class _CharT, class _Traits, class _Alloc>
inline basic_string<_CharT,_Traits,_Alloc>
operator+(const basic_string<_CharT,_Traits,_Alloc>& __s,
          const basic_string<_CharT,_Traits,_Alloc>& __y)
{
  typedef basic_string<_CharT,_Traits,_Alloc> _Str;
  typedef typename _Str::_Reserve_t _Reserve_t;
# ifdef __GNUC__
  // gcc counts this as a function
  _Str __result  = _Str(_Reserve_t(),__s.size() + __y.size());
# else
  _Str __result(_Reserve_t(), __s.size() + __y.size());
# endif
  __result.append(__s);
  __result.append(__y);
  return __result;
}

template <class _CharT, class _Traits, class _Alloc>
inline basic_string<_CharT,_Traits,_Alloc>
operator+(const _CharT* __s,
          const basic_string<_CharT,_Traits,_Alloc>& __y) {
  typedef basic_string<_CharT,_Traits,_Alloc> _Str;
  typedef typename _Str::_Reserve_t _Reserve_t;
  const size_t __n = _Traits::length(__s);
# ifdef __GNUC__
  _Str __result = _Str(_Reserve_t(), __n + __y.size());
# else
  _Str __result(_Reserve_t(), __n + __y.size());
# endif
  __result.append(__s, __s + __n);
  __result.append(__y);
  return __result;
}

template <class _CharT, class _Traits, class _Alloc>
inline basic_string<_CharT,_Traits,_Alloc>
operator+(_CharT __c,
          const basic_string<_CharT,_Traits,_Alloc>& __y) {
  typedef basic_string<_CharT,_Traits,_Alloc> _Str;
  typedef typename _Str::_Reserve_t _Reserve_t;
# ifdef __GNUC__
  _Str __result = _Str(_Reserve_t(), 1 + __y.size());
# else
  _Str __result(_Reserve_t(), 1 + __y.size());
# endif
  __result.push_back(__c);
  __result.append(__y);
  return __result;
}

template <class _CharT, class _Traits, class _Alloc>
inline basic_string<_CharT,_Traits,_Alloc>
operator+(const basic_string<_CharT,_Traits,_Alloc>& __x,
          const _CharT* __s) {
  typedef basic_string<_CharT,_Traits,_Alloc> _Str;
  typedef typename _Str::_Reserve_t _Reserve_t;
  const size_t __n = _Traits::length(__s);
# ifdef __GNUC__
  _Str __result = _Str(_Reserve_t(), __x.size() + __n, __x.get_allocator());
# else
  _Str __result(_Reserve_t(), __x.size() + __n, __x.get_allocator());
# endif
  __result.append(__x);
  __result.append(__s, __s + __n);
  return __result;
}

template <class _CharT, class _Traits, class _Alloc>
inline basic_string<_CharT,_Traits,_Alloc>
operator+(const basic_string<_CharT,_Traits,_Alloc>& __x,
          const _CharT __c) {
  typedef basic_string<_CharT,_Traits,_Alloc> _Str;
  typedef typename _Str::_Reserve_t _Reserve_t;
# ifdef __GNUC__
  _Str __result = _Str(_Reserve_t(), __x.size() + 1, __x.get_allocator());
# else
  _Str __result(_Reserve_t(), __x.size() + 1, __x.get_allocator());
# endif
  __result.append(__x);
  __result.push_back(__c);
  return __result;
}

// Operator== and operator!=

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator==(const basic_string<_CharT,_Traits,_Alloc>& __x,
           const basic_string<_CharT,_Traits,_Alloc>& __y) {
  return __x.size() == __y.size() &&
         _Traits::compare(__x.data(), __y.data(), __x.size()) == 0;
}

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator==(const _CharT* __s,
           const basic_string<_CharT,_Traits,_Alloc>& __y) {
  size_t __n = _Traits::length(__s);
  return __n == __y.size() && _Traits::compare(__s, __y.data(), __n) == 0;
}

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator==(const basic_string<_CharT,_Traits,_Alloc>& __x,
           const _CharT* __s) {
  size_t __n = _Traits::length(__s);
  return __x.size() == __n && _Traits::compare(__x.data(), __s, __n) == 0;
}

#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator!=(const basic_string<_CharT,_Traits,_Alloc>& __x,
           const basic_string<_CharT,_Traits,_Alloc>& __y) {
  return !(__x == __y);
}

#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator!=(const _CharT* __s,
           const basic_string<_CharT,_Traits,_Alloc>& __y) {
  return !(__s == __y);
}

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator!=(const basic_string<_CharT,_Traits,_Alloc>& __x,
           const _CharT* __s) {
  return !(__x == __s);
}



// Operator< (and also >, <=, and >=).

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator<(const basic_string<_CharT,_Traits,_Alloc>& __x,
          const basic_string<_CharT,_Traits,_Alloc>& __y) {
  return basic_string<_CharT,_Traits,_Alloc>
    ::_M_compare(_Make_ptr(__x.begin()), _Make_ptr(__x.end()), 
		 _Make_ptr(__y.begin()), _Make_ptr(__y.end())) < 0;
}

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator<(const _CharT* __s,
          const basic_string<_CharT,_Traits,_Alloc>& __y) {
  size_t __n = _Traits::length(__s);
  return basic_string<_CharT,_Traits,_Alloc>
    ::_M_compare(__s, __s + __n, _Make_ptr(__y.begin()), _Make_ptr(__y.end())) < 0;
}

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator<(const basic_string<_CharT,_Traits,_Alloc>& __x,
          const _CharT* __s) {
  size_t __n = _Traits::length(__s);
  return basic_string<_CharT,_Traits,_Alloc>
    ::_M_compare(_Make_ptr(__x.begin()), _Make_ptr(__x.end()), __s, __s + __n) < 0;
}

#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator>(const basic_string<_CharT,_Traits,_Alloc>& __x,
          const basic_string<_CharT,_Traits,_Alloc>& __y) {
  return __y < __x;
}


template <class _CharT, class _Traits, class _Alloc>
inline bool
operator<=(const basic_string<_CharT,_Traits,_Alloc>& __x,
           const basic_string<_CharT,_Traits,_Alloc>& __y) {
  return !(__y < __x);
}

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator>=(const basic_string<_CharT,_Traits,_Alloc>& __x,
           const basic_string<_CharT,_Traits,_Alloc>& __y) {
  return !(__x < __y);
}

#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator>(const _CharT* __s,
          const basic_string<_CharT,_Traits,_Alloc>& __y) {
  return __y < __s;
}

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator>(const basic_string<_CharT,_Traits,_Alloc>& __x,
          const _CharT* __s) {
  return __s < __x;
}

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator<=(const _CharT* __s,
           const basic_string<_CharT,_Traits,_Alloc>& __y) {
  return !(__y < __s);
}

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator<=(const basic_string<_CharT,_Traits,_Alloc>& __x,
           const _CharT* __s) {
  return !(__s < __x);
}

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator>=(const _CharT* __s,
           const basic_string<_CharT,_Traits,_Alloc>& __y) {
  return !(__s < __y);
}

template <class _CharT, class _Traits, class _Alloc>
inline bool
operator>=(const basic_string<_CharT,_Traits,_Alloc>& __x,
           const _CharT* __s) {
  return !(__x < __s);
}

// Swap.

#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER

template <class _CharT, class _Traits, class _Alloc>
inline void swap(basic_string<_CharT,_Traits,_Alloc>& __x,
                 basic_string<_CharT,_Traits,_Alloc>& __y) {
  __x.swap(__y);
}

#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */

// I/O.  

#ifdef __STL_USE_NEW_IOSTREAMS

template <class _CharT, class _Traits>
inline bool
__sgi_string_fill(basic_ostream<_CharT, _Traits>& __os,
                  basic_streambuf<_CharT, _Traits>* __buf,
                  size_t __n)
{
  _CharT __f = __os.fill();
  size_t __i;
  bool __ok = true;

  for (__i = 0; __i < __n; ++__i)
    __ok == __ok && !_Traits::eq_int_type(__buf->sputc(__f), _Traits::eof());
  return __ok;
}

template <class _CharT, class _Traits, class _Alloc>
basic_ostream<_CharT, _Traits>&
operator<<(basic_ostream<_CharT, _Traits>& __os, 
           const basic_string<_CharT,_Traits,_Alloc>& __s)
{
  typename __STL_VENDOR_STD::basic_ostream<_CharT, _Traits>::sentry __sentry(__os);
  bool __ok = false;

  if (__sentry) {
    __ok = true;
    size_t __n = __s.size();
    size_t __pad_len = 0;
    const bool __left = bool(__os.flags() & ios::left);
    const size_t __w = __os.width(0);
    basic_streambuf<_CharT, _Traits>* __buf = __os.rdbuf();

    if (__w > 0) {
      __n = min(__w, __n);
      __pad_len = __w - __n;
    }
    
    if (!__left)
      __ok = __sgi_string_fill(__os, __buf, __pad_len);    

    __ok = __ok && __buf->sputn(__s.data(), __n) == __n;

    if (__left)
      __ok = __ok && __sgi_string_fill(__os, __buf, __pad_len);
  }

  if (!__ok)
    __os.setstate(ios_base::failbit);

  return __os;
}

template <class _CharT, class _Traits, class _Alloc>
basic_istream<_CharT, _Traits>& 
operator>>(basic_istream<_CharT, _Traits>& __is,
           basic_string<_CharT,_Alloc>& __s)
{
  typename __STL_VENDOR_STD::basic_istream<_CharT, _Traits>::sentry __sentry(__is);

  if (__sentry) {
    basic_streambuf<_CharT, _Traits>* __buf = __is.rdbuf();
    const ctype<_CharT>& __ctype = use_facet<ctype<_CharT> >(__is.getloc());

    __s.clear();
    size_t __n = __is.width(0);
    if (__n == 0)
      __n = __STATIC_CAST(size_t,-1);
    else
      __s.reserve(__n);
    

    while (__n-- > 0) {
      typename _Traits::int_type __c1 = __buf->sbumpc();
      if (_Traits::eq_int_type(__c1, _Traits::eof())) {
        __is.setstate(ios_base::eofbit);
        break;
      }
      else {
        _CharT __c = _Traits::to_char_type(__c1);

        if (__ctype.is(ctype_base::space, __c)) {
          if (_Traits::eq_int_type(__buf->sputbackc(__c), _Traits::eof()))
            __is.setstate(ios_base::failbit);
          break;
        }
        else
          __s.push_back(__c);
      }
    }
    
    // If we have read no characters, then set failbit.
    if (__s.size() == 0)
      __is.setstate(ios_base::failbit);
  }
  else
    __is.setstate(ios_base::failbit);

  return __is;
}

template <class _CharT, class _Traits, class _Alloc>    
basic_istream<_CharT, _Traits>& 
getline(basic_istream<_CharT, _Traits>& __is,
        basic_string<_CharT,_Traits,_Alloc>& __s,
        _CharT __delim)
{
  size_t __nread = 0;
  typename __STL_VENDOR_STD::basic_istream<_CharT, _Traits>::sentry __sentry(__is, true);
  if (__sentry) {
    basic_streambuf<_CharT, _Traits>* __buf = __is.rdbuf();
    __s.clear();

    int __c1;
    while (__nread < __s.max_size()) {
      int __c1 = __buf->sbumpc();
      if (_Traits::eq_int_type(__c1, _Traits::eof())) {
        __is.setstate(ios_base::eofbit);
        break;
      }
      else {
        ++__nread;
        _CharT __c = _Traits::to_char_type(__c1);
        if (!_Traits::eq(__c, __delim)) 
          __s.push_back(__c);
        else
          break;              // Character is extracted but not appended.
      }
    }
  }
  if (__nread == 0 || __nread >= __s.max_size())
    __is.setstate(ios_base::failbit);

  return __is;
}

template <class _CharT, class _Traits, class _Alloc>    
inline basic_istream<_CharT, _Traits>& 
getline(basic_istream<_CharT, _Traits>& __is,
        basic_string<_CharT,_Traits,_Alloc>& __s)
{
  return getline(__is, __s, '\n');
}

#else /* __STL_USE_NEW_IOSTREAMS */

inline void __sgi_string_fill(ostream& __os, streambuf* __buf, size_t __n)
{
  char __f = __os.fill();
  size_t __i;

  for (__i = 0; __i < __n; ++__i) __buf->sputc(__f);
}

template <class _CharT, class _Traits, class _Alloc>
ostream& operator<<(ostream& __os, 
                    const basic_string<_CharT,_Traits,_Alloc>& __s)
{
  streambuf* __buf = __os.rdbuf();
  if (__buf) {
    size_t __n = __s.size();
    size_t __pad_len = 0;
    const bool __left = bool(__os.flags() & ios::left);
    const size_t __w = __os.width();

    if (__w > 0) {
      __n = min(__w, __n);
      __pad_len = __w - __n;
    }
    
    if (!__left)
      __sgi_string_fill(__os, __buf, __pad_len);
  
    const size_t __nwritten = __buf->sputn(__s.data(), __n);

    if (__left)
      __sgi_string_fill(__os, __buf, __pad_len);

    if (__nwritten != __n)
      __os.clear(__os.rdstate() | ios::failbit);

    __os.width(0);
  }
  else
    __os.clear(__os.rdstate() | ios::badbit);

  return __os;
}

template <class _CharT, class _Traits, class _Alloc>
istream& operator>>(istream& __is, basic_string<_CharT,_Traits,_Alloc>& __s)
{
  if (!__is)
    return __is;

  streambuf* __buf = __is.rdbuf();
  if (__buf) {
    if (__is.flags() & ios::skipws) {
      _CharT __c;
      do {
        int __c1 = __buf->sbumpc();
        if (__c1 == EOF) {
          __is.clear(__is.rdstate() | ios::eofbit | ios::failbit);
          break;
        }
        else
          __c = _Traits::to_char_type(__c1);
      }
      while (isspace((unsigned char) __c));

      if (__buf->sputbackc(__c) == EOF)
        __is.clear(__is.rdstate() | ios::failbit);
    }

    // If we arrive at end of file (or fail for some other reason) while
    // still discarding whitespace, then we don't try to read the string.
    if (__is) {
      __s.clear();

      size_t __n = __is.width();
      if (__n == 0)
        __n = __STATIC_CAST(size_t,-1);
      else
        __s.reserve(__n);

      while (__n-- > 0) {
        int __c1 = __buf->sbumpc();
        if (__c1 == EOF) {
          __is.clear(__is.rdstate() | ios::eofbit);
          break;
        }
        else {
          _CharT __c = _Traits::to_char_type(__c1);

          if (isspace((unsigned char) __c)) {
            if (__buf->sputbackc(__c) == EOF)
              __is.clear(__is.rdstate() | ios::failbit);
            break;
          }
          else
            __s.push_back(__c);
        }
      }
    
      // If we have read no characters, then set failbit.
      if (__s.size() == 0)
        __is.clear(__is.rdstate() | ios::failbit);
    }

    __is.width(0);
  }
  else                          // We have no streambuf.
    __is.clear(__is.rdstate() | ios::badbit);

  return __is;
}

template <class _CharT, class _Traits, class _Alloc>    
istream& getline(istream& __is,
                 basic_string<_CharT,_Traits,_Alloc>& __s,
                 _CharT __delim)
{
  streambuf* __buf = __is.rdbuf();
  if (__buf) {
    size_t __nread = 0;
    if (__is) {
      __s.clear();

      while (__nread < __s.max_size()) {
        int __c1 = __buf->sbumpc();
        if (__c1 == EOF) {
          __is.clear(__is.rdstate() | ios::eofbit);
          break;
        }
        else {
          ++__nread;
          _CharT __c = _Traits::to_char_type(__c1);
          if (!_Traits::eq(__c, __delim)) 
            __s.push_back(__c);
          else
            break;              // Character is extracted but not appended.
        }
      }
    }

    if (__nread == 0 || __nread >= __s.max_size())
      __is.clear(__is.rdstate() | ios::failbit);
  }
  else
    __is.clear(__is.rdstate() | ios::badbit);

  return __is;
}

template <class _CharT, class _Traits, class _Alloc>    
inline istream& 
getline(istream& __is, basic_string<_CharT,_Traits,_Alloc>& __s)
{
  return getline(__is, __s, '\n');
}

#endif /* __STL_USE_NEW_IOSTREAMS */

template <class _CharT, class _Traits, class _Alloc>
void _S_string_copy(const basic_string<_CharT,_Traits,_Alloc>& __s,
                    _CharT* __buf,
                    size_t __n)
{
  if (__n > 0) {
    __n = min(__n - 1, __s.size());
    copy(__s.begin(), __s.begin() + __n, __buf);
    __buf[__n] = _CharT();
  }
}

template <class _CharT, class _Traits, class _Alloc>
const char* 
__get_c_string(const basic_string<_CharT,_Traits,_Alloc>& __str) { 
  return __str.c_str(); 
}

// ------------------------------------------------------------
// Typedefs

#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma reset woff 1174
#pragma reset woff 1375
#endif

__STL_END_NAMESPACE

#include <stl_hash_fun.h>

__STL_BEGIN_NAMESPACE

template <class _CharT, class _Traits, class _Alloc>
size_t __stl_string_hash(const basic_string<_CharT,_Traits,_Alloc>& __s) {
  unsigned long __h = 0;
  for (basic_string<_CharT,_Traits,_Alloc>::const_pointer __i = _Make_ptr(__s.begin());
       __i != _Make_ptr(__s.end());
       ++__i)
    __h = 5*__h + *__i;
  return size_t(__h);
}

#ifdef __STL_CLASS_PARTIAL_SPECIALIZATION

template <class _CharT, class _Traits, class _Alloc>
struct hash<basic_string<_CharT,_Traits,_Alloc> > {
  size_t operator()(const basic_string<_CharT,_Traits,_Alloc>& __s) const
    { return __stl_string_hash(__s); }
};

#else

__STL_TEMPLATE_NULL struct hash<string> {
  size_t operator()(const string& __s) const
    { return __stl_string_hash(__s); }
};

# if defined (__STL_WCHAR_T)
__STL_TEMPLATE_NULL struct hash<wstring> {
  size_t operator()(const wstring& __s) const
    { return __stl_string_hash(__s); }
};
# endif

#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */

// cleanup
#  undef __size_type__
#  undef size_type
#  undef __iterator__
#  undef __const_iterator__
#  undef iterator
#  undef _Make_iterator
#  undef _Make_const_iterator
#  undef _Make_ptr

__STL_END_NAMESPACE

# endif /*__STL_USE_NATIVE_STRING */
#endif /* __SGI_STL_STRING */


// Local Variables:
// mode:C++
// End:

