/* **********************************************************************************
 *
 * Copyright (c) Microsoft Corporation. All rights reserved.
 *
 * This source code is subject to terms and conditions of the Shared Source License
 * for IronPython. A copy of the license can be found in the License.html file
 * at the root of this distribution. If you can not locate the Shared Source License
 * for IronPython, please send an email to ironpy@microsoft.com.
 * By using this source code in any fashion, you are agreeing to be bound by
 * the terms of the Shared Source License for IronPython.
 *
 * You must not remove this notice, or any other, from this software.
 *
 * **********************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

using System.Reflection;

using System.Globalization;

using IronMath;

namespace IronPython.Runtime {

    /// <summary>
    /// The type the user gets when doing type('abc') or str.  This allows us
    /// to extend String with the methods in StringOps.  StringDynamicType also
    /// defines overloads for adding and multiplying strings so:
    /// 
    /// Ops.GetDynamicType('abc').Multiply('abc', 3) and such works properly.
    /// </summary>
    public class StringDynamicType : OpsReflectedType {
        public StringDynamicType()
            : base("str", typeof(string), typeof(StringOps), typeof(ExtensibleString), new CallTarget1(FastNew)) {
        }

        internal static object FastNew(object x) {
            if (x == null) {
                return "None";
            }
            if (x is string) {
                // check ascii
                string s = (string)x;
                for (int i = 0; i < s.Length; i++) {
                    if (s[i] > '\x80') return StringOps.Make((PythonType)Ops.GetDynamicTypeFromType(typeof(String)), s, null);
                }
                return s;
            }
            return Ops.ToString(x);
        }

        public override object Add(object self, object other) {
            string s = other as string;
            if (s == null) return Ops.NotImplemented;
            return ((string)self) + s;
        }

        public override object Multiply(object self, object other) {
            if (other is int) {
                return StringOps.Multiply((string)self, (int)other);
            } else if (other is bool) {
                return StringOps.Multiply((string)self, ((bool)other) ? 1 : 0);
            } else if (other is BigInteger) {
                BigInteger bi = other as BigInteger;
                int size;
                if (bi.AsInt32(out size))
                    return StringOps.Multiply((string)self, size);
                else
                    throw Ops.OverflowError("long int too large to convert to int");
            } else if (other is ExtensibleInt) {
                return StringOps.Multiply((string)self, ((ExtensibleInt)other).value);
            }
            return Ops.NotImplemented;
        }

        public override object ReverseMultiply(object self, object other) {
            if (other is int) {
                return StringOps.Multiply((string)self, (int)other);
            } else if (other is bool) {
                return StringOps.Multiply((string)self, ((bool)other) ? 1 : 0);
            } else if (other is BigInteger) {
                BigInteger bi = other as BigInteger;
                int size;
                if (bi.AsInt32(out size))
                    return StringOps.Multiply((string)self, size);
                else
                    throw Ops.OverflowError("long int too large to convert to int");
            } else if (other is ExtensibleInt) {
                return StringOps.Multiply((string)self, ((ExtensibleInt)other).value);
            }
            return Ops.NotImplemented;
        }

        public override object Mod(object self, object other) {
            return Ops.ToPython(new StringFormatter((string)self, other).Format());
        }
    }

    /// <summary>
    /// ExtensibleString is the base class that is used for types the user defines
    /// that derive from string.  It carries along with it the string's value and
    /// our converter recognizes it as a string.
    /// </summary>
    public class ExtensibleString : ICodeFormattable, IPythonComparable {
        private string self;

        public ExtensibleString() { this.self = String.Empty; }
        public ExtensibleString(string self) { this.self = self; }

        public string Value {
            get { return self; }
        }

        public override string ToString() {
            return self;
        }
        #region ICodeFormattable Members

        public virtual string ToCodeString() {
            return StringOps.Quote(self);
        }

        #endregion

        #region IPythonComparable Members
        public object CompareTo(object other) {
            return StringOps.Compare(self, other);
        }

        public object GreaterThan(object other) {
            object res = StringOps.Compare(self, other);
            if (res is int) return ((int)res) > 0;
            return Ops.NotImplemented;
        }

        public object LessThan(object other) {
            object res = StringOps.Compare(self, other);
            if (res is int) return ((int)res) < 0;
            return Ops.NotImplemented;
        }

        public object GreaterThanOrEqual(object other) {
            object res = StringOps.Compare(self, other);
            if (res is int) return ((int)res) >= 0;
            return Ops.NotImplemented;
        }

        public object LessThanOrEqual(object other) {
            object res = StringOps.Compare(self, other);
            if (res is int) return ((int)res) <= 0;
            return Ops.NotImplemented;
        }

        #endregion
    }

    /// <summary>
    /// StringOps is the static class that is concatenated with the built-in
    /// System.String type to present to the user the final Python type presentation.
    /// 
    /// Here we define all of the methods that a Python user would see when doing dir('abc').
    /// If the user is running in a CLS aware context they will also see all of the methods
    /// defined in the CLS System.String type.
    /// </summary>
    public static class StringOps {
        private static Dictionary<string, EncodingInfo> codecs;

        #region Python Constructors

        [PythonName("__new__")]
        public static object Make(PythonType cls) {
            if (cls == TypeCache.String) {
                return "";
            } else {
                return cls.ctor.Call(cls);
            }
        }

        [PythonName("__new__")]
        public static object Make(PythonType cls, object x) {
            if (cls == TypeCache.String) {
                return StringDynamicType.FastNew(x);
            } else {
                return cls.ctor.Call(cls, x);
            }
        }

        [PythonName("__new__")]
        public static object Make(PythonType cls, string s, string encoding) {
            if (cls == TypeCache.String) {
                return Decode(s, encoding);
            } else {
                return cls.ctor.Call(cls, s, encoding);
            }
        }
        #endregion

        #region Python __ methods

        [PythonName("__contains__")]
        public static bool Contains(string s, string item) {
            return s.Contains(item);
        }

        [PythonName("__len__")]
        public static int GetLength(string s) {
            return s.Length;
        }

        [PythonName("__getitem__")]
        public static string __getitem__(string s, int index) {
            return Ops.Char2String(s[Ops.FixIndex(index, s.Length)]);
        }

        [PythonName("__getitem__")]
        public static string __getitem__(string s, Slice slice) {
            if (slice == null) throw Ops.TypeError("string indicies must be slices or integers");
            int start, stop, step;
            slice.indices(s.Length, out start, out stop, out step);
            if (step == 1) {
                return stop > start ? s.Substring(start, stop - start) : String.Empty;
            } else {
                int index = 0;
                char[] newData;
                if (step > 0) {
                    if (start > stop) return String.Empty;

                    int icnt = (stop - start + step - 1) / step;
                    newData = new char[icnt];
                    for (int i = start; i < stop; i += step) {
                        newData[index++] = s[i];
                    }
                } else {
                    if (start < stop) return String.Empty;

                    int icnt = (stop - start + step + 1) / step;
                    newData = new char[icnt];
                    for (int i = start; i > stop; i += step) {
                        newData[index++] = s[i];
                    }
                }
                return new string(newData);
            }
        }

        [PythonName("__getslice__")]
        public static string GetSlice(string self, int x, int y) {
            return __getitem__(self, new Slice(x, y));
        }

        [PythonName("__mod__")]
        public static string Modulus(string self, object other) {
            return new StringFormatter(self, other).Format();
        }

        [PythonName("__mul__")]
        public static string Multiply(string s, int count) {
            if (count <= 0) return String.Empty;

            long size = (long)s.Length * (long)count;
            if (size > Int32.MaxValue) throw Ops.OverflowError("repeated string is too long");

            int sz = s.Length;
            if (sz == 1) return new string(s[0], count);

            StringBuilder ret = new StringBuilder(sz * count);
            ret.Insert(0, s, count);
            // the above code is MUCH faster than the simple loop
            //for (int i=0; i < count; i++) ret.Append(s);
            return ret.ToString();
        }

        #endregion

        #region Public Python methods

        [PythonName("capitalize")]
        public static string Capitalize(string self) {
            if (self.Length == 0) return self;
            return Char.ToUpper(self[0]) + self.Substring(1).ToLower();
        }

        //  default fillchar (padding char) is a space
        [PythonName("center")]
        public static string Center(string self, int width) {
            return Center(self, width, ' ');
        }

        [PythonName("center")]
        public static string Center(string self, int width, char fillchar) {
            int spaces = width - self.Length;
            if (spaces <= 0) return self;

            StringBuilder ret = new StringBuilder(width);
            ret.Append(fillchar, spaces / 2);
            ret.Append(self);
            ret.Append(fillchar, (spaces + 1) / 2);
            return ret.ToString();
        }

        [PythonName("count")]
        public static int Count(string self, string sub) {
            return Count(self, sub, 0, self.Length);
        }

        [PythonName("count")]
        public static int Count(string self, string sub, int start) {
            return Count(self, sub, start, self.Length);
        }

        [PythonName("count")]
        public static int Count(string self, string ssub, int start, int end) {
            if (ssub == null) throw Ops.TypeError("expected string for 'sub' argument, got NoneType");
            string v = self;
            if (v.Length == 0) return 0;

            start = Ops.FixSliceIndex(start, self.Length);
            end = Ops.FixSliceIndex(end, self.Length);

            int count = 0;
            while (true) {
                if (end <= start) break;
                int index = v.IndexOf(ssub, start, end - start);
                if (index == -1) break;
                count++;
                start = index + ssub.Length;
            }
            return count;
        }

        [PythonName("decode")]
        public static string Decode(string s) {
            return Decode(s, null);
        }

        [PythonName("decode")]
        public static string Decode(string s, string encoding) {
            return RawDecode(s, encoding);
        }

        [PythonName("encode")]
        public static string Encode(string s, string encoding) {
            return RawEncode(s, encoding);
        }

        [PythonName("endswith")]
        public static bool EndsWith(string self, string suffix) {
            if (suffix == null) throw Ops.TypeError("expected string, got NoneType");
            return self.EndsWith(suffix);
        }

        //  Indexing is 0-based. Need to deal with negative indices
        //  (which mean count backwards from end of sequence)
        //  +---+---+---+---+---+ 
        //  | a | b | c | d | e |
        //  +---+---+---+---+---+ 
        //    0   1   2   3   4    
        //   -5  -4  -3  -2  -1

        [PythonName("endswith")]
        public static bool EndsWith(string self, string suffix, int start) {
            if (suffix == null) throw Ops.TypeError("expected string, got NoneType");
            int len = self.Length;
            if (start > len) return false;
            // map the negative indice to its positive counterpart
            if (start < 0) {
                start += len;
                if (start < 0) start = 0;
            }
            return self.Substring(start).EndsWith(suffix);
        }

        //  With optional start, test beginning at that position (the char at that index is
        //  included in the test). With optional end, stop comparing at that position (the 
        //  char at that index is not included in the test)
        [PythonName("endswith")]
        public static bool EndsWith(string self, string suffix, int start, int end) {
            if (suffix == null) throw Ops.TypeError("expected string, got NoneType");
            int len = self.Length;
            if (start > len) return false;
            // map the negative indices to their positive counterparts
            else if (start < 0) {
                start += len;
                if (start < 0) start = 0;
            }
            if (end >= len) return self.Substring(start).EndsWith(suffix);
            else if (end < 0) {
                end += len;
                if (end < 0) return false;
            }
            if (end < start) return false;
            return self.Substring(start, end - start).EndsWith(suffix);
        }

        [PythonName("expandtabs")]
        public static string ExpandTabs(string self) {
            return ExpandTabs(self, 8);
        }

        [PythonName("expandtabs")]
        public static string ExpandTabs(string self, int tabsize) {
            StringBuilder ret = new StringBuilder(self.Length * 2);
            string v = self;
            int col = 0;
            for (int i = 0; i < v.Length; i++) {
                char ch = v[i];
                switch (ch) {
                    case '\n':
                    case '\r': col = 0; ret.Append(ch); break;
                    case '\t':
                        if (tabsize > 0) {
                            int tabs = tabsize - (col % tabsize);
                            ret.Append(' ', tabs);
                        }
                        break;
                    default:
                        col++;
                        ret.Append(ch);
                        break;
                }
            }
            return ret.ToString();
        }

        [PythonName("find")]
        public static int Find(string self, string sub) {
            if (sub == null) throw Ops.TypeError("expected string, got NoneType");
            if (sub.Length == 1) return self.IndexOf(sub[0]);
            CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
            return c.IndexOf(self, sub, CompareOptions.Ordinal);
            //            char start = sub[0];
            //
            //            if (sub.Length == 1) return self.IndexOf(start);
            //
            //            int index = 0;
            //            int max = self.Length-sub.Length;
            //
            //            while (index < max) {
            //                int i = self.IndexOf(start, index);
            //                if (i == -1) break;
            //                if (String.CompareOrdinal(self, index, sub, 0, sub.Length) == 0) {
            //                    return i;
            //                }
            //                index = i+1;
            //            }
            //
            //            return -1;
            //!!! too slow return self.IndexOf(sub);
        }

        [PythonName("find")]
        public static int Find(string self, string sub, int start) {
            if (sub == null) throw Ops.TypeError("expected string, got NoneType");
            return self.IndexOf(sub, Ops.FixSliceIndex(start, self.Length));
        }

        [PythonName("find")]
        public static int Find(string self, string sub, int start, int end) {
            if (sub == null) throw Ops.TypeError("expected string, got NoneType");
            start = Ops.FixSliceIndex(start, self.Length);
            end = Ops.FixSliceIndex(end, self.Length);

            return self.IndexOf(sub, start, end - start);
        }

        [PythonName("index")]
        public static int Index(string self, string sub) {
            if (sub == null) throw Ops.TypeError("expected string, got NoneType");
            return Index(self, sub, 0, self.Length);
        }

        [PythonName("index")]
        public static int Index(string self, string sub, int start) {
            if (sub == null) throw Ops.TypeError("expected string, got NoneType");
            return Index(self, sub, start, self.Length);
        }

        [PythonName("index")]
        public static int Index(string self, string sub, int start, int end) {
            if (sub == null) throw Ops.TypeError("expected string, got NoneType");
            int ret = Find(self, sub, start, end);
            if (ret == -1) throw Ops.ValueError("substring {0} not found in {1}", sub, self);
            return ret;
        }

        [PythonName("isalnum")]
        public static bool IsAlnum(string self) {
            if (self.Length == 0) return false;
            string v = self;
            for (int i = v.Length - 1; i >= 0; i--) {
                if (!Char.IsLetterOrDigit(v, i)) return false;
            }
            return true;
        }

        [PythonName("isalpha")]
        public static bool IsAlpha(string self) {
            if (self.Length == 0) return false;
            string v = self;
            for (int i = v.Length - 1; i >= 0; i--) {
                if (!Char.IsLetter(v, i)) return false;
            }
            return true;
        }

        [PythonName("isdigit")]
        public static bool IsDigit(string self) {
            if (self.Length == 0) return false;
            string v = self;
            for (int i = v.Length - 1; i >= 0; i--) {
                if (!Char.IsDigit(v, i)) return false;
            }
            return true;
        }

        [PythonName("isspace")]
        public static bool IsSpace(string self) {
            if (self.Length == 0) return false;
            string v = self;
            for (int i = v.Length - 1; i >= 0; i--) {
                if (!Char.IsWhiteSpace(v, i)) return false;
            }
            return true;
        }

        [PythonName("islower")]
        public static bool IsLower(string self) {
            if (self.Length == 0) return false;
            string v = self;
            bool hasLower = false;
            for (int i = v.Length - 1; i >= 0; i--) {
                if (!hasLower && Char.IsLower(v, i)) hasLower = true;
                if (Char.IsUpper(v, i)) return false;
            }
            return hasLower;
        }

        [PythonName("isupper")]
        public static bool IsUpper(string self) {
            if (self.Length == 0) return false;
            string v = self;
            bool hasUpper = false;
            for (int i = v.Length - 1; i >= 0; i--) {
                if (!hasUpper && Char.IsUpper(v, i)) hasUpper = true;
                if (Char.IsLower(v, i)) return false;
            }
            return hasUpper;
        }

        //  return true if self is a titlecased string and there is at least one
        //  character in self; also, uppercase characters may only follow uncased
        //  characters (e.g. whitespace) and lowercase characters only cased ones. 
        //  return false otherwise.
        [PythonName("istitle")]
        public static bool IsTitle(string self) {
            if (self == null || self.Length == 0) return false;

            string v = self;
            bool prevCharCased = false, currCharCased = false, containsUpper = false;
            for (int i = 0; i < v.Length; i++) {
                if (Char.IsUpper(v, i)) {
                    containsUpper = true;
                    if (prevCharCased)
                        return false;
                    else
                        currCharCased = true;
                } else if (Char.IsLower(v, i))
                    if (!prevCharCased)
                        return false;
                    else
                        currCharCased = true;
                else
                    currCharCased = false;
                prevCharCased = currCharCased;
            }

            //  if we've gone through the whole string and haven't encountered any rule 
            //  violations but also haven't seen an Uppercased char, then this is not a 
            //  title e.g. '\n', all whitespace etc.
            if (!containsUpper) return false;

            return true;
        }

        //  Return a string which is the concatenation of the strings 
        //  in the sequence seq. The separator between elements is the 
        //  string providing this method
        [PythonName("join")]
        public static object Join(string self, IEnumerator seq) {
            StringBuilder ret = new StringBuilder();
            if (!seq.MoveNext()) return "";

            // check if we have just a sequnce of just one value - if so just
            // return that value.
            object curVal = seq.Current;
            if (!seq.MoveNext()) return Converter.ConvertToString(curVal);

            AppendJoin(curVal, 0, ret);

            int index = 1;
            do {
                ret.Append(self);

                AppendJoin(seq.Current, index, ret);

                index++;
            } while (seq.MoveNext());

            return ret.ToString();
        }

        [PythonName("ljust")]
        public static string LJust(string self, int width) {
            return LJust(self, width, ' ');
        }

        [PythonName("ljust")]
        public static string LJust(string self, int width, char fillchar) {
            int spaces = width - self.Length;
            if (spaces <= 0) return self;

            StringBuilder ret = new StringBuilder(width);
            ret.Append(self);
            ret.Append(fillchar, spaces);
            return ret.ToString();
        }

        [PythonName("lower")]
        public static string Lower(string self) {
            return self.ToLower();
        }

        private static readonly char[] Whitespace = new char[] { ' ', '\t', '\n', '\r', '\f' };
        [PythonName("lstrip")]
        public static string LStrip(string self) {
            return self.TrimStart(Whitespace);
        }

        [PythonName("lstrip")]
        public static string LStrip(string self, string chars) {
            if (chars == null) return LStrip(self);
            return self.TrimStart(chars.ToCharArray());
        }

        [PythonName("replace")]
        public static string Replace(string self, string old, string new_) {
            if (old == null) throw Ops.TypeError("expected string for 'old' argument, got NoneType");
            if (old.Length == 0) return ReplaceEmpty(self, new_, self.Length + 1);
            return self.Replace(old, new_);
        }

        [PythonName("replace")]
        public static string Replace(string self, string old, string new_, int maxsplit) {
            if (old == null) throw Ops.TypeError("expected string for 'old' argument, got NoneType");
            if (maxsplit == -1) return Replace(self, old, new_);
            if (old.Length == 0) return ReplaceEmpty(self, new_, maxsplit);

            string v = self;
            StringBuilder ret = new StringBuilder(v.Length);

            int index;
            int start = 0;

            while (maxsplit > 0 && (index = v.IndexOf(old, start)) != -1) {
                ret.Append(v.Substring(start, index - start));
                ret.Append(new_);
                start = index + old.Length;
                maxsplit--;
            }
            ret.Append(v.Substring(start));

            return ret.ToString();
        }

        [PythonName("rfind")]
        public static int RFind(string self, string sub) {
            if (sub == null) throw Ops.TypeError("expected string, got NoneType");
            return RFind(self, sub, 0, self.Length);
        }

        [PythonName("rfind")]
        public static int RFind(string self, string sub, int start) {
            if (sub == null) throw Ops.TypeError("expected string, got NoneType");
            return RFind(self, sub, start, self.Length);
        }

        [PythonName("rfind")]
        public static int RFind(string self, string sub, int start, int end) {
            if (sub == null) throw Ops.TypeError("expected string, got NoneType");
            if (sub.Length == 0) return self.Length;

            start = Ops.FixSliceIndex(start, self.Length);
            end = Ops.FixSliceIndex(end, self.Length);
            //Console.WriteLine("count {0}, {1}, {2}", end-start-sub.self.Length, self.Length, start);
            return self.LastIndexOf(sub, end - 1, end - start);
        }

        [PythonName("rindex")]
        public static int RIndex(string self, string sub) {
            return RIndex(self, sub, 0, self.Length);
        }

        [PythonName("rindex")]
        public static int RIndex(string self, string sub, int start) {
            return RIndex(self, sub, start, self.Length);
        }

        [PythonName("rindex")]
        public static int RIndex(string self, string sub, int start, int end) {
            int ret = RFind(self, sub, start, end);
            if (ret == -1) throw Ops.ValueError("substring {0} not found in {1}", sub, self);
            return ret;
        }

        [PythonName("rjust")]
        public static string RJust(string self, int width) {
            return RJust(self, width, ' ');
        }

        [PythonName("rjust")]
        public static string RJust(string self, int width, char fillchar) {
            int spaces = width - self.Length;
            if (spaces <= 0) return self;

            StringBuilder ret = new StringBuilder(width);
            ret.Append(fillchar, spaces);
            ret.Append(self);
            return ret.ToString();
        }

        //  when no maxsplit arg is given then just use split
        [PythonName("rsplit")]
        public static List RSplit(string self) {
            return Split(self, (char[])null, -1);
        }

        [PythonName("rsplit")]
        public static List RSplit(string self, string sep) {
            return Split(self, sep, -1);
        }

        [PythonName("rsplit")]
        public static List RSplit(string self, string sep, int maxsplit) {

            //  rsplit works like split but needs to split from the right;
            //  reverse the original string (and the sep), split, reverse 
            //  the split list and finally reverse each element of the list
            string reversed = Reverse(self);
            if (sep != null) sep = Reverse(sep);
            List temp = null, ret = null;
            temp = Split(reversed, sep, maxsplit);
            temp.Reverse();
            if (temp.Count != 0)
                ret = new List();
            foreach (string s in temp)
                ret.AddNoLock(Reverse(s));
            return ret;
        }

        [PythonName("rstrip")]
        public static string RStrip(string self) {
            return self.TrimEnd(Whitespace);
        }

        [PythonName("rstrip")]
        public static string RStrip(string self, string chars) {
            if (chars == null) return RStrip(self);
            return self.TrimEnd(chars.ToCharArray());
        }

        [PythonName("split")]
        public static List Split(string self) {
            return Split(self, (char[])null, -1);
        }

        [PythonName("split")]
        public static List Split(string self, string sep) {
            return Split(self, sep, -1);
        }

        [PythonName("split")]
        public static List Split(string self, string sep, int maxsplit) {
            if (sep == null) return Split(self, (char[])null, maxsplit);

            if (sep.Length == 0) {
                throw Ops.ValueError("empty separator");
            } else if (sep.Length == 1) {
                return Split(self, new char[] { sep[0] }, maxsplit);
            } else {
                return Split(self, new string[] { sep }, maxsplit);
            }
        }
        //
        //        //!!! split with non-char sep

        [PythonName("splitlines")]
        public static List SplitLines(string self) {
            return SplitLines(self, false);
        }

        [PythonName("splitlines")]
        public static List SplitLines(string self, bool keepends) {
            List ret = new List();
            int i, linestart;
            for (i = 0, linestart = 0; i < self.Length; i++) {
                if (self[i] == '\n' || self[i] == '\r' || self[i] == '\x2028') {
                    //  special case of "\r\n" as end of line marker
                    if (i < self.Length - 1 && self[i] == '\r' && self[i + 1] == '\n') {
                        if (keepends)
                            ret.AddNoLock(self.Substring(linestart, i - linestart + 2));
                        else
                            ret.AddNoLock(self.Substring(linestart, i - linestart));
                        linestart = i + 2;
                        i++;
                    } else { //'\r', '\n', or unicode new line as end of line marker
                        if (keepends)
                            ret.AddNoLock(self.Substring(linestart, i - linestart + 1));
                        else
                            ret.AddNoLock(self.Substring(linestart, i - linestart));
                        linestart = i + 1;
                    }
                }
            }
            //  the last line needs to be accounted for if it is not empty
            if (i - linestart != 0)
                ret.AddNoLock(self.Substring(linestart, i - linestart));
            return ret;
        }

        [PythonName("startswith")]
        public static bool StartsWith(string self, string prefix) {
            if (prefix == null) throw Ops.TypeError("expected string, got NoneType");
            return self.StartsWith(prefix);
        }

        [PythonName("startswith")]
        public static bool StartsWith(string self, string prefix, int start) {
            if (prefix == null) throw Ops.TypeError("expected string, got NoneType");
            int len = self.Length;
            if (start > len) return false;
            if (start < 0) {
                start += len;
                if (start < 0) start = 0;
            }
            return self.Substring(start).StartsWith(prefix);
        }

        [PythonName("startswith")]
        public static bool StartsWith(string self, string prefix, int start, int end) {
            if (prefix == null) throw Ops.TypeError("expected string, got NoneType");
            int len = self.Length;
            if (start > len) return false;
            // map the negative indices to their positive counterparts
            else if (start < 0) {
                start += len;
                if (start < 0) start = 0;
            }
            if (end >= len) return self.Substring(start).StartsWith(prefix);
            else if (end < 0) {
                end += len;
                if (end < 0) return false;
            }
            if (end < start) return false;
            return self.Substring(start, end - start).StartsWith(prefix);
        }

        [PythonName("strip")]
        public static string Strip(string self) {
            return self.Trim();
        }

        [PythonName("strip")]
        public static string Strip(string self, string chars) {
            if (chars == null) return Strip(self);
            return self.Trim(chars.ToCharArray());
        }

        [PythonName("swapcase")]
        public static string SwapCase(string self) {
            StringBuilder ret = new StringBuilder(self);
            for (int i = 0; i < ret.Length; i++) {
                char ch = ret[i];
                if (Char.IsUpper(ch)) ret[i] = Char.ToLower(ch);
                else if (Char.IsLower(ch)) ret[i] = Char.ToUpper(ch);
            }
            return ret.ToString();
        }

        [PythonName("title")]
        public static string Title(string self) {
            if (self == null || self.Length == 0) return self;

            char[] retchars = self.ToCharArray();
            bool prevCharCased = false;
            bool currCharCased = false;
            int i = 0;
            do {
                if (Char.IsUpper(retchars[i]) || Char.IsLower(retchars[i])) {
                    if (!prevCharCased)
                        retchars[i] = Char.ToUpper(retchars[i]);
                    else
                        retchars[i] = Char.ToLower(retchars[i]);
                    currCharCased = true;
                } else {
                    currCharCased = false;
                }
                i++;
                prevCharCased = currCharCased;
            }
            while (i < retchars.Length);
            return new string(retchars);
        }

        [PythonName("translate")]
        public static string Translate(string self, string table) {
            return Translate(self, table, (string)null);
        }

        [PythonName("translate")]
        public static string Translate(string self, string table, string deletechars) {
            if (table == null) throw Ops.TypeError("expected string, got NoneType");
            if (table.Length != 256)
                throw Ops.ValueError("translation table must be 256 characters long");
            if (self.Length == 0) return self;
            StringBuilder ret = new StringBuilder();
            for (int i = 0, idx = 0; i < self.Length; i++) {
                if (deletechars == null || !deletechars.Contains(Char.ToString(self[i]))) {
                    idx = (int)self[i];
                    if (idx >= 0 && idx < 256) ret.Append(table[idx]);
                }
            }
            return ret.ToString();
        }

        [PythonName("upper")]
        public static string Upper(string self) {
            return self.ToUpper();
        }

        [PythonName("zfill")]
        public static string ZFill(string self, int width) {
            int spaces = width - self.Length;
            if (spaces <= 0) return self;

            StringBuilder ret = new StringBuilder(width);
            if (self.Length > 0 && IsSign(self[0])) {
                ret.Append(self[0]);
                ret.Append('0', spaces);
                ret.Append(self.Substring(1));
            } else {
                ret.Append('0', spaces);
                ret.Append(self);
            }
            return ret.ToString();
        }
        #endregion

        [PythonName("__eq__")]
        public static object Equals(string x, object other) {
            if (other is string) {
                return String.Equals(x, other as string);
            } else if (other is ExtensibleString) {
                return String.Equals(x, ((ExtensibleString)other).Value);
            }
            return Ops.NotImplemented;
        }

        public static bool EqualsRetBool(string x, object other) {
            if (other is string) {
                return string.Equals(x, other as string);
            } else if (other is ExtensibleString) {
                return string.Equals(x, ((ExtensibleString)other).Value);
            }
            return Ops.DynamicEqualRetBool(x, other);
        }

        [PythonName("__ne__")]
        public static object NotEquals(string x, object other) {
            if (other is string) {
                return !String.Equals(x, other as string);
            } else if (other is ExtensibleString) {
                return !String.Equals(x, ((ExtensibleString)other).Value);
            }
            return Ops.NotImplemented;
        }

        [PythonName("__cmp__")]
        public static object Compare(string self, object obj) {
            if (obj == null) return 1;

            string otherStr;

            if (obj is string) {
                otherStr = (string)obj;
            } else if (obj is ExtensibleString) {
                otherStr = ((ExtensibleString)obj).Value;
            } else {
                return Ops.NotImplemented;
            }

            int ret = string.CompareOrdinal(self, otherStr);
            return ret == 0 ? 0 : (ret < 0 ? -1 : +1);
        }

        #region Internal implementation details

        internal static IEnumerator GetEnumerator(string s) {
            // make an enumerator that produces strings instead of chars
            return new PythonStringEnumerator(s);
        }

        internal static string Quote(string s) {

            bool isUnicode = false;
            StringBuilder b = new StringBuilder(s.Length + 5);
            char quote = '\'';
            if (s.IndexOf('\'') != -1 && s.IndexOf('\"') == -1) {
                quote = '\"';
            }
            b.Append(quote);
            b.Append(ReprEncode(s, quote, ref isUnicode));
            b.Append(quote);
            if (isUnicode) return "u" + b.ToString();
            return b.ToString();
        }

        internal static string ReprEncode(string s, ref bool isUnicode) {
            return ReprEncode(s, (char)0, ref isUnicode);
        }

        internal static bool TryGetEncoding(string name, out Encoding encoding) {
            if (name == null) {
                encoding = Ops.State.DefaultEncoding;
                return true;
            }

            if (codecs == null) MakeCodecsDict();

            name = name.ToLower().Replace('-', '_');

            EncodingInfo encInfo;
            if (codecs.TryGetValue(name, out encInfo)) {
                encoding = encInfo.GetEncoding();
                return true;
            }

            encoding = null;
            return false;
        }


        #endregion

        #region Private implementation details

        private static void AppendJoin(object value, int index, StringBuilder sb) {
            string strVal;
            Conversion conv;

            if ((strVal = value as string) != null) {
                sb.Append(strVal.ToString());
            } else if ((strVal = Converter.TryConvertToString(value, out conv)) != null &&
                conv != Conversion.None) {
                sb.Append(strVal);
            } else {
                throw Ops.TypeError("sequence item {0}: expected string, {1} found", index.ToString(), Ops.GetDynamicType(value).__name__);
            }
        }

        private static string ReplaceEmpty(string self, string new_, int maxsplit) {
            if (maxsplit == 0) return self;

            string v = self;
            int max = maxsplit > v.Length ? v.Length : maxsplit;
            StringBuilder ret = new StringBuilder(v.Length * (new_.Length + 1));
            for (int i = 0; i < max; i++) {
                ret.Append(new_);
                ret.Append(v[i]);
            }
            if (maxsplit > max) {
                ret.Append(new_);
            }

            return ret.ToString();
        }

        private static string Reverse(string s) {
            if (s.Length == 0 || s.Length == 1) return s;
            char[] chars = s.ToCharArray();
            char[] rchars = new char[s.Length];
            for (int i = s.Length - 1, j = 0; i >= 0; i--, j++) {
                rchars[j] = chars[i];
            }
            return new string(rchars);
        }

        private static string ReprEncode(string s, char quote, ref bool isUnicode) {
            // in the common case we don't need to encode anything, so we
            // lazily create the StringBuilder only if necessary.
            StringBuilder b = null;
            for (int i = 0; i < s.Length; i++) {
                char ch = s[i];

                if (ch >= 0x7f) isUnicode = true;
                switch (ch) {
                    case '\\': ReprInit(ref b, s, i); b.Append("\\\\"); break;
                    case '\t': ReprInit(ref b, s, i); b.Append("\\t"); break;
                    case '\n': ReprInit(ref b, s, i); b.Append("\\n"); break;
                    case '\r': ReprInit(ref b, s, i); b.Append("\\r"); break;
                    default:
                        if (quote != 0 && ch == quote) {
                            ReprInit(ref b, s, i);
                            b.Append('\\'); b.Append(ch);
                        } else if (ch < ' ' || (ch >= 0x7f && ch <= 0xff)) {
                            ReprInit(ref b, s, i);
                            b.AppendFormat("\\x{0:x2}", (int)ch);
                        } else if (ch > 0xff) {
                            ReprInit(ref b, s, i);
                            b.AppendFormat("\\u{0:x4}", (int)ch);
                        } else if (b != null) {
                            b.Append(ch);
                        }
                        break;
                }
            }

            if (b == null) return s;
            return b.ToString();
        }

        private static void ReprInit(ref StringBuilder sb, string s, int c) {
            if (sb != null) return;

            sb = new StringBuilder(s, 0, c, s.Length);
        }

        private static bool IsSign(char ch) {
            return ch == '+' || ch == '-';
        }

        private static Encoding GetEncoding(string encoding) {
            Encoding enc;
            if (TryGetEncoding(encoding, out enc)) {
                return enc;
            }

            throw Ops.LookupError("unknown encoding: {0}", encoding);
        }

        private static string RawDecode(string s, string encoding) {
            if (encoding == "raw-unicode-escape") {
                return LiteralParser.ParseString(s, true, true);
            }

            Encoding e;
            if (TryGetEncoding(encoding, out e)) {
                // CLR's encoder exceptions have a 1-1 mapping w/ Python's encoder exceptions
                // so we just clone the encoding & set the fallback to throw
                e = (Encoding)e.Clone();
                e.DecoderFallback = DecoderFallback.ExceptionFallback;
                return e.GetString(ToByteArray(s));
            }

            // look for user-registered codecs
            Tuple codecTuple = Modules.PythonCodecs.Lookup(encoding);
            if (codecTuple != null) {
                return UserDecodeOrEncode(codecTuple[Modules.PythonCodecs.DecoderIndex], s);
            }

            throw Ops.LookupError("unknown encoding: {0}", encoding);

        }

        private static string RawEncode(string s, string encoding) {
            if (encoding == "raw-unicode-escape") {
                bool fUnicode = false;
                return ReprEncode(s, ref fUnicode);
            }

            Encoding e;
            if (TryGetEncoding(encoding, out e)) {
                // CLR's encoder exceptions have a 1-1 mapping w/ Python's encoder exceptions
                // so we just clone the encoding & set the fallback to throw
                e = (Encoding)e.Clone();
                e.EncoderFallback = EncoderFallback.ExceptionFallback;

                return FromByteArray(e.GetBytes(s));
            }

            // look for user-registered codecs
            Tuple codecTuple = Modules.PythonCodecs.Lookup(encoding);
            if (codecTuple != null) {
                return UserDecodeOrEncode(codecTuple[Modules.PythonCodecs.EncoderIndex], s);
            }

            throw Ops.LookupError("unknown encoding: {0}", encoding);
        }

        private static string UserDecodeOrEncode(object function, string data) {
            object res = Ops.Call(function, data);

            string strRes = res as string;
            if (strRes != null) return strRes;

            // tuple is string, bytes used, we just want the string...
            Tuple t = res as Tuple;
            if (t == null) throw Ops.TypeError("expected tuple, but found {0}", Ops.GetDynamicType(res).__name__);

            return Converter.ConvertToString(t[0]);
        }

        private static void MakeCodecsDict() {
            Dictionary<string, EncodingInfo> d = new Dictionary<string, EncodingInfo>();
            EncodingInfo[] encs = Encoding.GetEncodings();
            for (int i = 0; i < encs.Length; i++) {
                string lowerName = encs[i].Name.ToLower();
                // setup well-known mappings, for everything
                // else we'll store as lower case w/ _                
                switch (lowerName) {
                    case "us-ascii":
                        d["ascii"] = encs[i];
                        d["646"] = encs[i];
                        d["us"] = encs[i];
                        break;
                    case "iso-8859-1":
                        d["latin_1"] = encs[i];
                        d["latin1"] = encs[i];
                        break;
                    case "utf-8":
                        d["utf8"] = encs[i];
                        break;
                    case "utf-16":
                        d["utf_16_le"] = encs[i];
                        // utf-16 in CPython already writes the BOM, so we don't 
                        // want to replace it w/ ours that doesn't.
                        continue;
                    case "unicodeFFFE": // big endian unicode                    
                        d["utf_16_be"] = encs[i];
                        break;
                }

                string pyName = lowerName.Replace('-', '_');

                d[pyName] = encs[i];
            }

            codecs = d;
        }

        private static byte[] ToByteArray(string s) {
            byte[] ret = new byte[s.Length];
            for (int i = 0; i < s.Length; i++) {
                if (s[i] < 0x100) ret[i] = (byte)s[i];
                else throw Ops.UnicodeDecodeError("'ascii' codec can't decode byte {0:X} in position {1}: ordinal not in range", (int)ret[i], i);
            }
            return ret;
        }

        private static string FromByteArray(byte[] bytes1, byte[] bytes2) {
            StringBuilder b = new StringBuilder(bytes1.Length + bytes2.Length);
            for (int i = 0; i < bytes1.Length; i++) {
                b.Append((char)bytes1[i]);
            }
            for (int i = 0; i < bytes2.Length; i++) {
                b.Append((char)bytes2[i]);
            }
            return b.ToString();
        }


        private static string FromByteArray(byte[] bytes) {
            StringBuilder b = new StringBuilder(bytes.Length);
            for (int i = 0; i < bytes.Length; i++) {
                b.Append((char)bytes[i]);
            }
            return b.ToString();
        }

        private static List SplitEmptyString(bool separators) {
            List ret = List.MakeEmptyList(1);
            if (separators) {
                ret.AddNoLock(String.Empty);
            }
            return ret;
        }

        private static List Split(string self, char[] seps, int maxsplit) {
            if (self == String.Empty) {
                return SplitEmptyString(seps != null);
            } else {
                string[] r = null;
                //  If the optional second argument sep is absent or None, the words are separated 
                //  by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed);
                if (seps == null)
                    r = maxsplit == -1 ? self.Split(seps, StringSplitOptions.RemoveEmptyEntries)
                                            : self.Split(seps, maxsplit + 1, StringSplitOptions.RemoveEmptyEntries);
                else
                    r = maxsplit == -1 ? self.Split(seps)
                                            : self.Split(seps, maxsplit + 1);
                List ret = List.MakeEmptyList(r.Length);
                foreach (string s in r) ret.AddNoLock(s);
                return ret;
            }
        }

        private static List Split(string self, string[] seps, int maxsplit) {
            if (self == String.Empty) {
                return SplitEmptyString(seps != null);
            } else {
                string[] r = maxsplit == -1 ? self.Split(seps, StringSplitOptions.None)
                                            : self.Split(seps, maxsplit + 1, StringSplitOptions.None);
                List ret = List.MakeEmptyList(r.Length);
                foreach (string s in r) ret.AddNoLock(s);
                return ret;
            }
        }

        private class PythonStringEnumerator : IEnumerator {
            private string s;
            private int i;

            public PythonStringEnumerator(string s) {
                this.s = s;
                this.Reset();
            }
            #region IEnumerator Members

            public void Reset() {
                i = -1;
            }

            public object Current {
                get {
                    return Ops.Char2String(s[i]);
                }
            }

            public bool MoveNext() {
                i++;
                return i < s.Length;
            }

            #endregion

        }

        #endregion

    }
}
