private static extern SQLite3.Result CreateFunction(
			IntPtr db,
			string zFunctionName,
			int nArg,
			TextEncoding eTextRep,
			IntPtr pApp,
			Action<IntPtr, int, IntPtr> xFunc,
			Action<IntPtr, int, IntPtr> xStep,
			Action<IntPtr, int, IntPtr> xFinal
		);
        public static bool TryEncode(this char value, Span<byte> buffer, out int bytesWritten, TextEncoding encoding = TextEncoding.Utf8)
        {
            if (encoding == TextEncoding.Utf16)
            {
                if (buffer.Length < 2)
                {
                    bytesWritten = 0;
                    return false;
                }
                buffer[0] = (byte)value;
                buffer[1] = (byte)(value >> 8);
                bytesWritten = 2;
                return true;
            }

            if (encoding == TextEncoding.Utf8) {
                if (buffer.Length < 1) {
                    bytesWritten = 0;
                    return false;
                }

                // fast path for ASCII
                if (value <= 127) {
                    buffer[0] = (byte)value;
                    bytesWritten = 1;
                    return true;
                }

                // TODO: This can be directly encoded to SpanByte. There is no conversion between spans yet
                var encoded = new Utf8EncodedCodePoint(value);
                bytesWritten = encoded.Length;
                if (buffer.Length < bytesWritten) {
                    bytesWritten = 0;
                    return false;
                }

                buffer[0] = encoded.Byte0;
                if (bytesWritten > 1) {
                    buffer[1] = encoded.Byte1;
                }
                if (bytesWritten > 2) {
                    buffer[2] = encoded.Byte2;
                }
                if (bytesWritten > 3) {
                    buffer[3] = encoded.Byte3;
                }
                return true;
            }

            throw new NotImplementedException();
        }
Beispiel #3
0
        /// <summary>
        ///		Returns the proper <see cref="Encoding" /> for the given <see cref="TextEncoding" />.
        /// </summary>
        /// <param name="e">The <see cref="TextEncoding" /> you want the <see cref="Encoding" /> for.</param>
        /// <returns>A <see cref="Encoding" /> for the given <see cref="TextEncoding" />.</returns>
        /// <exceptions cref="InvalidEnumArgumentException">
        ///		The value specified is outside the range of valid values.
        /// </exceptions>
        internal static Encoding GetEncoding(TextEncoding e)
        {
            switch(e) {
                case TextEncoding.IsoLatin1:
                    return latin1;

                case TextEncoding.Utf16:
                    return utf16LE;

                case TextEncoding.Utf16BE:
                    return utf16BE;

                case TextEncoding.Utf8:
                    return utf8;

                default:
                    throw new InvalidEnumArgumentException("e", (int)e, typeof(TextEncoding));
            }
        }
Beispiel #4
0
        internal static void ParseEncodingByte(byte[] rawData, int encByteOffset, int stringOffset, out Encoding encoding, out TextEncoding textEncoding)
        {
            if (rawData.Length <= encByteOffset || rawData.Length < stringOffset) {
                throw new ID3ParseException("Frame size mismatch.");
            }

            switch (rawData[encByteOffset]) {
                case 0x00:
                    encoding = latin1;
                    textEncoding = TextEncoding.IsoLatin1;
                    break;

                case 0x01:
                    if (rawData.Length < stringOffset + 2) {
                        throw new ID3ParseException("Frame size mismatch.");
                    }

                    if (rawData[stringOffset] == 0xFE && rawData[stringOffset + 1] == 0xFF) {
                        encoding = utf16BE;
                    } else if (rawData[stringOffset] == 0xFF && rawData[stringOffset + 1] == 0xFE) {
                        encoding = utf16LE;
                    } else {
                        throw new ID3ParseException("Invalid Byte Order Mask.");
                    }
                    textEncoding = TextEncoding.Utf16;
                    break;

                case 0x02:
                    encoding = utf16BE;
                    textEncoding = TextEncoding.Utf16BE;
                    break;

                case 0x03:
                    encoding = utf8;
                    textEncoding = TextEncoding.Utf8;
                    break;

                default:
                    throw new ID3ParseException("Unknown TextEncoding.");
            }
        }
Beispiel #5
0
 public void WriteString(string s, int len = 0)
 {
     Debug.Assert(TextEncoding.GetByteCount(s) <= WriteSpaceLeft);
     WritePosition += TextEncoding.GetBytes(s, 0, len == 0 ? s.Length : len, Buffer, WritePosition);
 }
Beispiel #6
0
        /// <summary>
        /// Asynchronously reads data as text with the given timeout.
        /// </summary>
        /// <param name="timeout">The timeout.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A <see cref="System.String" /> that contains the results of decoding the specified sequence of bytes.
        /// </returns>
        public async Task <string> ReadTextAsync(TimeSpan timeout, CancellationToken cancellationToken = default)
        {
            var buffer = await ReadDataAsync(timeout, cancellationToken).ConfigureAwait(false);

            return(buffer == null ? null : TextEncoding.GetString(buffer));
        }
Beispiel #7
0
 /// <summary>
 /// Send message text to all clients in asynchronous mode.
 /// </summary>
 /// <param name="text">The message text to be sent.</param>
 /// <param name="callback">The callback that will be called after sending operation.</param>
 /// <returns>An System.IAsyncResult collection that references the asynchronous send.</returns>
 public IEnumerable <IAsyncResult> BroadcastText(string text, AsyncCallback callback)
 {
     return(BroadcastMessage(TextEncoding.GetBytes(text), callback));
 }
Beispiel #8
0
 /// <summary>
 /// Send message text to specific clients in asynchronous mode with default encoding, see TextEncoding property.
 /// </summary>
 /// <param name="clientIDCollection">The clients' id collection to receive messsage.</param>
 /// <param name="text">The message text to be sent.</param>
 /// <param name="callback">The callback that will be called after sending operation.</param>
 /// <returns>An System.IAsyncResult collection that references the asynchronous send.</returns>
 public IEnumerable <IAsyncResult> SendTextAsync(IEnumerable <long> clientIDCollection, string text, AsyncCallback callback)
 {
     return(SendMessageAsync(clientIDCollection, TextEncoding.GetBytes(text), callback));
 }
Beispiel #9
0
 /// <summary>
 /// Send message text to specific client in synchronous mode with default encoding, see TextEncoding property.
 /// </summary>
 /// <param name="clientID">The client id to send messsage.</param>
 /// <param name="text">The message text to be sent.</param>
 /// <returns>The number of bytes sent to the server.</returns>
 public void SendText(long clientID, string text)
 {
     SendMessage(clientID, TextEncoding.GetBytes(text));
 }
        public static bool TryEncode(this ReadOnlySpan<char> value, Span<byte> buffer, out int bytesWritten, TextEncoding encoding = TextEncoding.Utf8)
        {
            if (encoding == TextEncoding.Utf16) {
                var valueBytes = value.Cast<char, byte>();
                if (buffer.Length < valueBytes.Length) {
                    bytesWritten = 0;
                    return false;
                }
                valueBytes.CopyTo(buffer);
                bytesWritten = valueBytes.Length;
                return true;
            }

            if (encoding == TextEncoding.Utf8) {
                var avaliableBytes = buffer.Length;
                bytesWritten = 0;
                for (int i = 0; i < value.Length; i++) {
                    var c = value[i];

                    var codepoint = (ushort)c;
                    if (codepoint <= 0x7f) // this if block just optimizes for ascii
                    {
                        if (bytesWritten + 1 > avaliableBytes) {
                            bytesWritten = 0;
                            return false;
                        }
                        buffer[bytesWritten++] = (byte)codepoint;
                    }
                    else {
                        Utf8EncodedCodePoint encoded;
                        if (!char.IsSurrogate(c))
                            encoded = new Utf8EncodedCodePoint(c);
                        else {
                            if (++i >= value.Length)
                                throw new ArgumentException("Invalid surrogate pair.", nameof(value));
                            char lowSurrogate = value[i];
                            encoded = new Utf8EncodedCodePoint(c, lowSurrogate);
                        }


                        if (bytesWritten + encoded.Length > avaliableBytes) {
                            bytesWritten = 0;
                            return false;
                        }

                        buffer[bytesWritten] = encoded.Byte0;
                        if (encoded.Length > 1) {
                            buffer[bytesWritten + 1] = encoded.Byte1;

                            if (encoded.Length > 2) {
                                buffer[bytesWritten + 2] = encoded.Byte2;

                                if (encoded.Length > 3) {
                                    buffer[bytesWritten + 3] = encoded.Byte3;
                                }
                            }
                        }

                        bytesWritten += encoded.Length;
                    }
                }
                return true;
            }

            throw new NotSupportedException();
        }
Beispiel #11
0
        private static void ParsePanelAnimatedNode(XElement Element, string FileName, string TrainPath, TrainManager.Train Train, int Car, TrainManager.CarSection CarSection, int GroupIndex)
        {
            System.Globalization.CultureInfo Culture = System.Globalization.CultureInfo.InvariantCulture;

            int    currentSectionElement   = 0;
            int    numberOfSectionElements = Element.Elements().Count();
            double invfac = numberOfSectionElements == 0 ? Loading.TrainProgressCurrentWeight : Loading.TrainProgressCurrentWeight / (double)numberOfSectionElements;

            foreach (XElement SectionElement in Element.Elements())
            {
                Loading.TrainProgress = Loading.TrainProgressCurrentSum + invfac * (double)currentSectionElement;
                if ((currentSectionElement & 4) == 0)
                {
                    System.Threading.Thread.Sleep(1);
                    if (Loading.Cancel)
                    {
                        return;
                    }
                }

                string Section = SectionElement.Name.LocalName;

                switch (SectionElement.Name.LocalName.ToLowerInvariant())
                {
                case "group":
                    if (GroupIndex == 0)
                    {
                        int n = 0;

                        foreach (XElement KeyNode in SectionElement.Elements())
                        {
                            string Key        = KeyNode.Name.LocalName;
                            string Value      = KeyNode.Value;
                            int    LineNumber = ((IXmlLineInfo)KeyNode).LineNumber;

                            switch (Key.ToLowerInvariant())
                            {
                            case "number":
                                if (Value.Length != 0 && !NumberFormats.TryParseIntVb6(Value, out n))
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;
                            }
                        }

                        if (n + 1 >= CarSection.Groups.Length)
                        {
                            Array.Resize(ref CarSection.Groups, n + 2);
                            CarSection.Groups[n + 1] = new TrainManager.ElementsGroup
                            {
                                Elements = new ObjectManager.AnimatedObject[] { },
                                Overlay  = true
                            };
                        }

                        ParsePanelAnimatedNode(SectionElement, FileName, TrainPath, Train, Car, CarSection, n + 1);
                    }
                    break;

                case "touch":
                    if (GroupIndex > 0)
                    {
                        Vector3 Position             = Vector3.Zero;
                        Vector3 Size                 = Vector3.Zero;
                        int     JumpScreen           = GroupIndex - 1;
                        int     SoundIndex           = -1;
                        Translations.Command Command = Translations.Command.None;
                        int CommandOption            = 0;

                        foreach (XElement KeyNode in SectionElement.Elements())
                        {
                            string Key        = KeyNode.Name.LocalName;
                            string Value      = KeyNode.Value;
                            int    LineNumber = ((IXmlLineInfo)KeyNode).LineNumber;

                            switch (Key.ToLowerInvariant())
                            {
                            case "position":
                            {
                                string[] s = Value.Split(',');
                                if (s.Length == 3)
                                {
                                    if (s[0].Length != 0 && !NumberFormats.TryParseDoubleVb6(s[0], out Position.X))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "X is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                    }
                                    if (s[1].Length != 0 && !NumberFormats.TryParseDoubleVb6(s[1], out Position.Y))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "Y is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                    }
                                    if (s[2].Length != 0 && !NumberFormats.TryParseDoubleVb6(s[2], out Position.Z))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "Z is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                    }
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Three arguments are expected in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                            }
                            break;

                            case "size":
                            {
                                string[] s = Value.Split(',');
                                if (s.Length == 3)
                                {
                                    if (s[0].Length != 0 && !NumberFormats.TryParseDoubleVb6(s[0], out Size.X))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "X is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                    }
                                    if (s[1].Length != 0 && !NumberFormats.TryParseDoubleVb6(s[1], out Size.Y))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "Y is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                    }
                                    if (s[2].Length != 0 && !NumberFormats.TryParseDoubleVb6(s[2], out Size.Z))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "Z is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                    }
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Three arguments are expected in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                            }
                            break;

                            case "jumpscreen":
                                if (Value.Length != 0 && !NumberFormats.TryParseIntVb6(Value, out JumpScreen))
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;

                            case "soundindex":
                                if (Value.Length != 0 && !NumberFormats.TryParseIntVb6(Value, out SoundIndex))
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;

                            case "command":
                            {
                                int i;
                                for (i = 0; i < Translations.CommandInfos.Length; i++)
                                {
                                    if (string.Compare(Value, Translations.CommandInfos[i].Name, StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        break;
                                    }
                                }
                                if (i == Translations.CommandInfos.Length || Translations.CommandInfos[i].Type != Translations.CommandType.Digital)
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                else
                                {
                                    Command = Translations.CommandInfos[i].Command;
                                }
                            }
                            break;

                            case "commandoption":
                                if (Value.Length != 0 && !NumberFormats.TryParseIntVb6(Value, out CommandOption))
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;
                            }
                        }
                        CreateTouchElement(CarSection.Groups[GroupIndex], Position, Size, JumpScreen, SoundIndex, Command, CommandOption);
                    }
                    break;

                case "include":
                {
                    foreach (XElement KeyNode in SectionElement.Elements())
                    {
                        string Key        = KeyNode.Name.LocalName;
                        string Value      = KeyNode.Value;
                        int    LineNumber = ((IXmlLineInfo)KeyNode).LineNumber;

                        switch (Key.ToLowerInvariant())
                        {
                        case "filename":
                        {
                            string File = OpenBveApi.Path.CombineFile(TrainPath, Value);
                            if (System.IO.File.Exists(File))
                            {
                                System.Text.Encoding e = TextEncoding.GetSystemEncodingFromFile(File);
                                ObjectManager.AnimatedObjectCollection a = AnimatedObjectParser.ReadObject(File, e);
                                if (a != null)
                                {
                                    for (int i = 0; i < a.Objects.Length; i++)
                                    {
                                        a.Objects[i].ObjectIndex = ObjectManager.CreateDynamicObject();
                                    }
                                    CarSection.Groups[GroupIndex].Elements = a.Objects;
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                            }
                        }
                        break;
                        }
                    }
                }
                break;
                }
            }
        }
Beispiel #12
0
        /// <summary>
        /// Asynchronously reads data as text with the given timeout.
        /// </summary>
        /// <param name="timeout">The timeout.</param>
        /// <param name="ct">The cancellation token.</param>
        /// <returns>A <see cref="System.String" /> that contains the results of decoding the specified sequence of bytes</returns>
        public async Task <string> ReadTextAsync(TimeSpan timeout, CancellationToken ct = default(CancellationToken))
        {
            var buffer = await ReadDataAsync(timeout, ct);

            return(buffer == null ? null : TextEncoding.GetString(buffer));
        }
        /// <summary>
        /// تبدیل یک رشته ایران سیستم به یونیکد
        /// </summary>
        /// <param name="textEncoding">کدپیج رشته ایران سیستم</param>
        /// <param name="iranSystemEncodedString">رشته ایران سیستم</param>
        /// <returns></returns>
        public static string UnicodeFrom(TextEncoding textEncoding, string iranSystemEncodedString)
        {
            // حذف فاصله های موجود در رشته
            iranSystemEncodedString = iranSystemEncodedString.Replace(" ", "");

            /// بازگشت در صورت خالی بودن رشته
            if (string.IsNullOrWhiteSpace(iranSystemEncodedString))
            {
                return(string.Empty);
            }

            // در صورتی که رشته تماماً عدد نباشد
            if (!IsNumber(iranSystemEncodedString))
            {
                /// تغییر ترتیب کاراکترها از آخر به اول
                iranSystemEncodedString = Reverse(iranSystemEncodedString);

                /// خارج کردن اعداد درون رشته
                iranSystemEncodedString = ExcludeNumbers(iranSystemEncodedString);
            }

            // وهله سازی از انکودینگ صحیح برای تبدیل رشته ایران سیستم به بایت
            Encoding encoding = Encoding.GetEncoding((int)textEncoding);

            // تبدیل رشته به بایت
            byte[] stringBytes = encoding.GetBytes(iranSystemEncodedString.Trim());


            // آرایه ای که بایت های معادل را در آن قرار می دهیم
            // مجموع تعداد بایت های رشته + بایت های اضافی محاسبه شده
            byte[] newStringBytes = new byte[stringBytes.Length + CountCharactersRequireTwoBytes(stringBytes)];

            int index = 0;

            // بررسی هر بایت و پیدا کردن بایت (های) معادل آن
            for (int i = 0; i < stringBytes.Length; ++i)
            {
                byte charByte = stringBytes[i];

                // اگر جز 128 بایت اول باشد که نیازی به تبدیل ندارد چون کد اسکی است
                if (charByte < 128)
                {
                    newStringBytes[index] = charByte;
                }
                else
                {
                    // اگر جز حروف یا اعداد بود معادلش رو قرار می دیم
                    if (CharactersMapper.ContainsKey(charByte))
                    {
                        newStringBytes[index] = CharactersMapper[charByte];
                    }
                }

                // اگر کاراکتر ایران سیستم "لا" بود چون کاراکتر متناظرش در عربی 1256 "ل" است و باید یک "ا" هم بعدش اضافه کنیم
                if (charByte == 242)
                {
                    newStringBytes[++index] = 199;
                }

                // اگر کاراکتر یکی از انواعی بود که بعدشان باید یک فاصله باشد
                // و در عین حال آخرین کاراکتر رشته نبود
                if (charactersWithSpaceAfter.Contains(charByte) && Array.IndexOf(stringBytes, charByte) != stringBytes.Length - 1)
                {
                    // یک فاصله بعد ان اضافه می کنیم
                    newStringBytes[++index] = 32;
                }

                index += 1;
            }

            // تبدیل به رشته و ارسال به فراخواننده
            byte[] unicodeContent = Encoding.Convert(encoding, Encoding.Unicode, newStringBytes);

            string convertedString = Encoding.Unicode.GetString(unicodeContent).Trim();

            return(IncludeNumbers(convertedString));
        }
        public static bool TryParseUInt32(ReadOnlySpan<byte> text, TextEncoding encoding, out uint value, out int bytesConsumed)
        {
            Precondition.Require(text.Length > 0);
            Precondition.Require(encoding == TextEncoding.Utf8 || text.Length > 1);

            value = 0;
            bytesConsumed = 0;

            if (text[0] == '0')
            {
                if (encoding == TextEncoding.Utf16)
                {
                    bytesConsumed = 2;
                    return text[1] == 0;
                }
                bytesConsumed = 1;
                return true;
            }

            for (int byteIndex = 0; byteIndex < text.Length; byteIndex++)
            {
                byte nextByte = text[byteIndex];
                if (nextByte < '0' || nextByte > '9')
                {
                    if (bytesConsumed == 0)
                    {
                        value = default(uint);
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                uint candidate = value * 10;
                candidate += (uint)nextByte - '0';
                if (candidate > value)
                {
                    value = candidate;
                }
                else
                {
                    return true;
                }
                bytesConsumed++;
                if (encoding == TextEncoding.Utf16)
                {
                    byteIndex++;
                    if (byteIndex >= text.Length || text[byteIndex] != 0)
                    {
                        return false;
                    }
                    bytesConsumed++;
                }
            }

            return true;
        }
Beispiel #15
0
 /// <summary>
 /// Gets the length of the body of this message.
 /// </summary>
 /// <returns>The length of the body of this message.</returns>
 protected override int GetBodyLength()
 {
     return(TextEncoding.GetByteCount(m_username));
 }
Beispiel #16
0
        /// <summary>Loads the sound set for a BVE4 or openBVE sound.cfg based train</summary>
        /// <param name="train">The train</param>
        /// <param name="FileName">The absolute on-disk path to the sound.cfg file</param>
        /// <param name="trainFolder">The absolute on-disk path to the train's folder</param>
        internal void Parse(string FileName, string trainFolder, TrainBase train)
        {
            //Default sound positions and radii

            //3D center of the car
            Vector3 center = Vector3.Zero;
            //Positioned to the left of the car, but centered Y & Z
            Vector3 left = new Vector3(-1.3, 0.0, 0.0);
            //Positioned to the right of the car, but centered Y & Z
            Vector3 right = new Vector3(1.3, 0.0, 0.0);
            //Positioned at the front of the car, centered X and Y
            Vector3 front = new Vector3(0.0, 0.0, 0.5 * train.Cars[train.DriverCar].Length);
            //Positioned at the position of the panel / 3D cab (Remember that the panel is just an object in the world...)
            Vector3 panel = new Vector3(train.Cars[train.DriverCar].Driver.X, train.Cars[train.DriverCar].Driver.Y, train.Cars[train.DriverCar].Driver.Z + 1.0);

            //Radius at which the sound is audible at full volume, presumably in m
            //TODO: All radii are much too small in external mode, but we can't change them by default.....

            Encoding Encoding = TextEncoding.GetSystemEncodingFromFile(FileName);

            // parse configuration file
            System.Globalization.CultureInfo Culture = System.Globalization.CultureInfo.InvariantCulture;
            List <string> Lines      = System.IO.File.ReadAllLines(FileName, Encoding).ToList();
            int           emptyLines = 0;

            for (int i = Lines.Count - 1; i >= 0; i--)
            {
                /*
                 * Strip comments and remove empty resulting lines etc.
                 *
                 * This fixes an error with some NYCTA content, which has
                 * a copyright notice instead of the file header specified....
                 */
                int j = Lines[i].IndexOf(';');
                if (j >= 0)
                {
                    Lines[i] = Lines[i].Substring(0, j).Trim();
                }
                else
                {
                    Lines[i] = Lines[i].Trim();
                }
                if (string.IsNullOrEmpty(Lines[i]))
                {
                    emptyLines++;
                }
            }

            if (Lines.Count == 0 || emptyLines == Lines.Count)
            {
                Plugin.currentHost.AddMessage(MessageType.Error, false, "Empty sound.cfg encountered in " + FileName + ".");
            }
            else if (string.Compare(Lines[0], "version 1.0", StringComparison.OrdinalIgnoreCase) != 0)
            {
                Plugin.currentHost.AddMessage(MessageType.Error, false, "Invalid file format encountered in " + FileName + ". The first line is expected to be \"Version 1.0\".");
            }
            string[] MotorFiles = new string[] { };
            double   invfac     = Lines.Count == 0 ? 0.1 : 0.1 / Lines.Count;

            for (int i = 0; i < Lines.Count; i++)
            {
                if (string.IsNullOrEmpty(Lines[i]))
                {
                    continue;
                }
                Plugin.CurrentProgress = Plugin.LastProgress + invfac * i;
                if ((i & 7) == 0)
                {
                    System.Threading.Thread.Sleep(1);
                    if (Plugin.Cancel)
                    {
                        return;
                    }
                }
                switch (Lines[i].ToLowerInvariant())
                {
                case "[run]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            if (!int.TryParse(a, System.Globalization.NumberStyles.Integer, Culture, out var k))
                            {
                                Plugin.currentHost.AddMessage(MessageType.Error, false, "Invalid index appeared at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                            }
                            else
                            {
                                if (k >= 0)
                                {
                                    for (int c = 0; c < train.Cars.Length; c++)
                                    {
                                        if (train.Cars[c].Sounds.Run == null)
                                        {
                                            train.Cars[c].Sounds.Run = new Dictionary <int, CarSound>();
                                        }

                                        if (train.Cars[c].Sounds.Run.ContainsKey(k))
                                        {
                                            train.Cars[c].Sounds.Run[k] = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.mediumRadius, center);
                                        }
                                        else
                                        {
                                            train.Cars[c].Sounds.Run.Add(k, new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.mediumRadius, center));
                                        }
                                    }
                                }
                                else
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, "RunIndex must be greater than or equal to zero at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                }
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[flange]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            if (!int.TryParse(a, System.Globalization.NumberStyles.Integer, Culture, out var k))
                            {
                                Plugin.currentHost.AddMessage(MessageType.Error, false, "Invalid index appeared at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                            }
                            else
                            {
                                if (k >= 0)
                                {
                                    for (int c = 0; c < train.Cars.Length; c++)
                                    {
                                        if (train.Cars[c].Sounds.Flange.ContainsKey(k))
                                        {
                                            train.Cars[c].Sounds.Flange[k] = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.mediumRadius, center);
                                        }
                                        else
                                        {
                                            train.Cars[c].Sounds.Flange.Add(k, new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.mediumRadius, center));
                                        }
                                    }
                                }
                                else
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, "FlangeIndex must be greater than or equal to zero at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                }
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[motor]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            if (!int.TryParse(a, System.Globalization.NumberStyles.Integer, Culture, out var k))
                            {
                                Plugin.currentHost.AddMessage(MessageType.Error, false, "Invalid index appeared at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                            }
                            else
                            {
                                if (k >= 0)
                                {
                                    if (k >= MotorFiles.Length)
                                    {
                                        Array.Resize(ref MotorFiles, k + 1);
                                    }
                                    MotorFiles[k] = Path.CombineFile(trainFolder, b);
                                    if (!System.IO.File.Exists(MotorFiles[k]))
                                    {
                                        Plugin.currentHost.AddMessage(MessageType.Error, true, "File " + MotorFiles[k] + " does not exist at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                        MotorFiles[k] = null;
                                    }
                                }
                                else
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, "MotorIndex must be greater than or equal to zero at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                }
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[switch]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            if (NumberFormats.TryParseIntVb6(a, out var switchIndex))
                            {
                                if (switchIndex < 0)
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, "SwitchIndex must be greater than or equal to zero at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                    continue;
                                }
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    int n = train.Cars[c].FrontAxle.PointSounds.Length;
                                    if (switchIndex >= n)
                                    {
                                        Array.Resize(ref train.Cars[c].FrontAxle.PointSounds, switchIndex + 1);
                                        Array.Resize(ref train.Cars[c].RearAxle.PointSounds, switchIndex + 1);
                                        for (int h = n; h < switchIndex; h++)
                                        {
                                            train.Cars[c].FrontAxle.PointSounds[h] = new CarSound();
                                            train.Cars[c].RearAxle.PointSounds[h]  = new CarSound();
                                        }
                                    }
                                    Vector3 frontaxle = new Vector3(0.0, 0.0, train.Cars[c].FrontAxle.Position);
                                    Vector3 rearaxle  = new Vector3(0.0, 0.0, train.Cars[c].RearAxle.Position);
                                    train.Cars[c].FrontAxle.PointSounds[switchIndex] = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, frontaxle);
                                    train.Cars[c].RearAxle.PointSounds[switchIndex]  = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, rearaxle);
                                }
                            }
                            else
                            {
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported index " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[brake]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            switch (a.ToLowerInvariant())
                            {
                            case "bc release high":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    train.Cars[c].CarBrake.AirHigh = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, center);
                                }

                                break;

                            case "bc release":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    train.Cars[c].CarBrake.Air = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, center);
                                }

                                break;

                            case "bc release full":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    train.Cars[c].CarBrake.AirZero = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, center);
                                }

                                break;

                            case "emergency":
                                train.Handles.EmergencyBrake.ApplicationSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.mediumRadius, center);
                                break;

                            case "emergencyrelease":
                                train.Handles.EmergencyBrake.ReleaseSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.mediumRadius, center);
                                break;

                            case "bp decomp":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    train.Cars[c].CarBrake.Release = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, center);
                                }

                                break;

                            default:
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                break;
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[compressor]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            for (int c = 0; c < train.Cars.Length; c++)
                            {
                                if (train.Cars[c].CarBrake.brakeType == BrakeType.Main)
                                {
                                    switch (a.ToLowerInvariant())
                                    {
                                    case "attack":
                                        train.Cars[c].CarBrake.airCompressor.StartSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.mediumRadius, center);
                                        break;

                                    case "loop":
                                        train.Cars[c].CarBrake.airCompressor.LoopSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.mediumRadius, center);
                                        break;

                                    case "release":
                                        train.Cars[c].CarBrake.airCompressor.EndSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.mediumRadius, center);
                                        break;

                                    default:
                                        Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                        break;
                                    }
                                }
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[suspension]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            switch (a.ToLowerInvariant())
                            {
                            case "left":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    train.Cars[c].Sounds.SpringL = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, left);
                                }

                                break;

                            case "right":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    train.Cars[c].Sounds.SpringR = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, right);
                                }

                                break;

                            default:
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                break;
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[horn]":
                    i++;
                    while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            try
                            {
                                switch (a.ToLowerInvariant())
                                {
                                //PRIMARY HORN (Enter)
                                case "primarystart":
                                    Plugin.currentHost.RegisterSound(Path.CombineFile(trainFolder, b), SoundCfgParser.largeRadius, out var primaryStart);
                                    train.Cars[train.DriverCar].Horns[0].StartSound     = primaryStart as SoundBuffer;
                                    train.Cars[train.DriverCar].Horns[0].SoundPosition  = front;
                                    train.Cars[train.DriverCar].Horns[0].StartEndSounds = true;
                                    break;

                                case "primaryend":
                                case "primaryrelease":
                                    Plugin.currentHost.RegisterSound(Path.CombineFile(trainFolder, b), SoundCfgParser.largeRadius, out var primaryEnd);
                                    train.Cars[train.DriverCar].Horns[0].EndSound       = primaryEnd as SoundBuffer;
                                    train.Cars[train.DriverCar].Horns[0].SoundPosition  = front;
                                    train.Cars[train.DriverCar].Horns[0].StartEndSounds = true;
                                    break;

                                case "primaryloop":
                                case "primary":
                                    Plugin.currentHost.RegisterSound(Path.CombineFile(trainFolder, b), SoundCfgParser.largeRadius, out var primaryLoop);
                                    train.Cars[train.DriverCar].Horns[0].LoopSound     = primaryLoop as SoundBuffer;
                                    train.Cars[train.DriverCar].Horns[0].SoundPosition = front;
                                    train.Cars[train.DriverCar].Horns[0].Loop          = false;
                                    break;

                                //SECONDARY HORN (Numpad Enter)
                                case "secondarystart":
                                    Plugin.currentHost.RegisterSound(Path.CombineFile(trainFolder, b), SoundCfgParser.largeRadius, out var secondaryStart);
                                    train.Cars[train.DriverCar].Horns[1].StartSound     = secondaryStart as SoundBuffer;
                                    train.Cars[train.DriverCar].Horns[1].SoundPosition  = front;
                                    train.Cars[train.DriverCar].Horns[1].StartEndSounds = true;
                                    break;

                                case "secondaryend":
                                case "secondaryrelease":
                                    Plugin.currentHost.RegisterSound(Path.CombineFile(trainFolder, b), SoundCfgParser.largeRadius, out var secondaryEnd);
                                    train.Cars[train.DriverCar].Horns[1].EndSound       = secondaryEnd as SoundBuffer;
                                    train.Cars[train.DriverCar].Horns[1].SoundPosition  = front;
                                    train.Cars[train.DriverCar].Horns[1].StartEndSounds = true;
                                    break;

                                case "secondaryloop":
                                case "secondary":
                                    Plugin.currentHost.RegisterSound(Path.CombineFile(trainFolder, b), SoundCfgParser.largeRadius, out var secondaryLoop);
                                    train.Cars[train.DriverCar].Horns[1].LoopSound     = secondaryLoop as SoundBuffer;
                                    train.Cars[train.DriverCar].Horns[1].SoundPosition = front;
                                    train.Cars[train.DriverCar].Horns[1].Loop          = false;
                                    break;

                                //MUSIC HORN
                                case "musicstart":
                                    Plugin.currentHost.RegisterSound(Path.CombineFile(trainFolder, b), SoundCfgParser.mediumRadius, out var musicStart);
                                    train.Cars[train.DriverCar].Horns[2].StartSound     = musicStart as SoundBuffer;
                                    train.Cars[train.DriverCar].Horns[2].SoundPosition  = front;
                                    train.Cars[train.DriverCar].Horns[2].StartEndSounds = true;
                                    break;

                                case "musicend":
                                case "musicrelease":
                                    Plugin.currentHost.RegisterSound(Path.CombineFile(trainFolder, b), SoundCfgParser.mediumRadius, out var musicEnd);
                                    train.Cars[train.DriverCar].Horns[2].EndSound       = musicEnd as SoundBuffer;
                                    train.Cars[train.DriverCar].Horns[2].SoundPosition  = front;
                                    train.Cars[train.DriverCar].Horns[2].StartEndSounds = true;
                                    break;

                                case "musicloop":
                                case "music":
                                    Plugin.currentHost.RegisterSound(Path.CombineFile(trainFolder, b), SoundCfgParser.mediumRadius, out var musicLoop);
                                    train.Cars[train.DriverCar].Horns[2].LoopSound     = musicLoop as SoundBuffer;
                                    train.Cars[train.DriverCar].Horns[2].SoundPosition = front;
                                    train.Cars[train.DriverCar].Horns[2].Loop          = true;
                                    break;

                                default:
                                    Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                    break;
                                }
                            }
                            catch
                            {
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "FileName contains illegal characters or is empty in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                            }
                        }

                        i++;
                    }
                    i--; break;

                case "[door]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            switch (a.ToLowerInvariant())
                            {
                            case "open left":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    train.Cars[c].Doors[0].OpenSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, left);
                                }

                                break;

                            case "open right":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    train.Cars[c].Doors[1].OpenSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, right);
                                }

                                break;

                            case "close left":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    train.Cars[c].Doors[0].CloseSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, left);
                                }

                                break;

                            case "close right":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    train.Cars[c].Doors[1].CloseSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, right);
                                }
                                break;

                            default:
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                break;
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[ats]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            if (!int.TryParse(a, System.Globalization.NumberStyles.Integer, Culture, out var k))
                            {
                                Plugin.currentHost.AddMessage(MessageType.Error, false, "Invalid index appeared at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                            }
                            else
                            {
                                if (k >= 0)
                                {
                                    int n = train.Cars[train.DriverCar].Sounds.Plugin.Length;
                                    if (k >= n)
                                    {
                                        Array.Resize(ref train.Cars[train.DriverCar].Sounds.Plugin, k + 1);
                                        for (int h = n; h < k; h++)
                                        {
                                            train.Cars[train.DriverCar].Sounds.Plugin[h] = new CarSound();
                                        }
                                    }

                                    train.Cars[train.DriverCar].Sounds.Plugin[k] = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                }
                                else
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Warning, false, "Index must be greater than or equal to zero at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                }
                            }
                        }

                        i++;
                    }
                    i--; break;

                case "[buzzer]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            switch (a.ToLowerInvariant())
                            {
                            case "correct":
                                train.SafetySystems.StationAdjust.AdjustAlarm = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            default:
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                break;
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[pilot lamp]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            switch (a.ToLowerInvariant())
                            {
                            case "on":
                                train.SafetySystems.PilotLamp.OnSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "off":
                                train.SafetySystems.PilotLamp.OffSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            default:
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                break;
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[brake handle]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            switch (a.ToLowerInvariant())
                            {
                            case "apply":
                                train.Handles.Brake.Increase = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "applyfast":
                                train.Handles.Brake.IncreaseFast = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "release":
                                train.Handles.Brake.Decrease = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "releasefast":
                                train.Handles.Brake.DecreaseFast = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "min":
                                train.Handles.Brake.Min = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "max":
                                train.Handles.Brake.Max = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            default:
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                break;
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[master controller]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            switch (a.ToLowerInvariant())
                            {
                            case "up":
                                train.Handles.Power.Increase = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "upfast":
                                train.Handles.Power.IncreaseFast = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "down":
                                train.Handles.Power.Decrease = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "downfast":
                                train.Handles.Power.DecreaseFast = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "min":
                                train.Handles.Power.Min = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "max":
                                train.Handles.Power.Max = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            default:
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                break;
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[reverser]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            switch (a.ToLowerInvariant())
                            {
                            case "on":
                                train.Handles.Reverser.EngageSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "off":
                                train.Handles.Reverser.ReleaseSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            default:
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                break;
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[breaker]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            switch (a.ToLowerInvariant())
                            {
                            case "on":
                                train.Cars[train.DriverCar].Breaker.Resume = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, panel);
                                break;

                            case "off":
                                train.Cars[train.DriverCar].Breaker.ResumeOrInterrupt = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.smallRadius, panel);
                                break;

                            default:
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                break;
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[others]":
                    i++;
                    while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            switch (a.ToLowerInvariant())
                            {
                            case "noise":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    if (train.Cars[c].Specs.IsMotorCar | c == train.DriverCar)
                                    {
                                        train.Cars[c].Sounds.Loop = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.mediumRadius, center);
                                    }
                                }

                                break;

                            case "shoe":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    train.Cars[c].CarBrake.Rub = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.mediumRadius, center);
                                }

                                break;

                            case "halt":
                                for (int c = 0; c < train.Cars.Length; c++)
                                {
                                    train.SafetySystems.PassAlarm.Sound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                }

                                break;

                            default:
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                break;
                            }
                        }
                        i++;
                    }
                    i--; break;

                case "[windscreen]":
                    i++; while (i < Lines.Count && !Lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
                        if (j >= 0)
                        {
                            string a = Lines[i].Substring(0, j).TrimEnd();
                            string b = Lines[i].Substring(j + 1).TrimStart();
                            switch (a.ToLowerInvariant())
                            {
                            case "raindrop":
                                train.Cars[train.DriverCar].Windscreen.DropSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "wetwipe":
                                train.Cars[train.DriverCar].Windscreen.Wipers.WetWipeSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "drywipe":
                                train.Cars[train.DriverCar].Windscreen.Wipers.DryWipeSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            case "switch":
                                train.Cars[train.DriverCar].Windscreen.Wipers.SwitchSound = new CarSound(Plugin.currentHost, trainFolder, FileName, i, b, SoundCfgParser.tinyRadius, panel);
                                break;

                            default:
                                Plugin.currentHost.AddMessage(MessageType.Warning, false, "Unsupported key " + a + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
                                break;
                            }
                        }
                        i++;
                    }
                    i--; break;
                }
            }
            // motor sound
            for (int c = 0; c < train.Cars.Length; c++)
            {
                if (train.Cars[c].Specs.IsMotorCar)
                {
                    if (train.Cars[c].Sounds.Motor is BVEMotorSound motorSound)
                    {
                        train.Cars[c].Sounds.Motor.Position = center;
                        for (int i = 0; i < motorSound.Tables.Length; i++)
                        {
                            motorSound.Tables[i].Buffer = null;
                            motorSound.Tables[i].Source = null;
                            for (int j = 0; j < motorSound.Tables[i].Entries.Length; j++)
                            {
                                int index = motorSound.Tables[i].Entries[j].SoundIndex;
                                if (index >= 0 && index < MotorFiles.Length && MotorFiles[index] != null)
                                {
                                    Plugin.currentHost.RegisterSound(MotorFiles[index], SoundCfgParser.mediumRadius, out var mS);
                                    motorSound.Tables[i].Entries[j].Buffer = mS as SoundBuffer;
                                }
                            }
                        }
                    }
                    else
                    {
                        Plugin.currentHost.AddMessage(MessageType.Error, false, "Unexpected motor sound model found in car " + c);
                    }
                }
            }
        }
Beispiel #17
0
 private ScriptOptions CreateOptions() => new ScriptOptions(_document, _document.Loop)
 {
     Element  = _script,
     Encoding = TextEncoding.Resolve(_script.CharacterSet)
 };
        private void ParsePanelAnimatedNode(XElement Element, string FileName, string TrainPath, TrainBase Train, int Car, CarSection CarSection, int GroupIndex)
        {
            System.Globalization.CultureInfo Culture = System.Globalization.CultureInfo.InvariantCulture;

            int    currentSectionElement   = 0;
            int    numberOfSectionElements = Element.Elements().Count();
            double invfac = numberOfSectionElements == 0 ? 1.0 : 1.0 / (double)numberOfSectionElements;

            foreach (XElement SectionElement in Element.Elements())
            {
                Plugin.CurrentProgress = Plugin.CurrentProgress + invfac * (double)currentSectionElement;
                if ((currentSectionElement & 4) == 0)
                {
                    System.Threading.Thread.Sleep(1);
                    if (Plugin.Cancel)
                    {
                        return;
                    }
                }

                string Section = SectionElement.Name.LocalName;

                switch (SectionElement.Name.LocalName.ToLowerInvariant())
                {
                case "group":
                    if (GroupIndex == 0)
                    {
                        int n = 0;

                        foreach (XElement KeyNode in SectionElement.Elements())
                        {
                            string Key        = KeyNode.Name.LocalName;
                            string Value      = KeyNode.Value;
                            int    LineNumber = ((IXmlLineInfo)KeyNode).LineNumber;

                            switch (Key.ToLowerInvariant())
                            {
                            case "number":
                                if (Value.Length != 0 && !NumberFormats.TryParseIntVb6(Value, out n))
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;
                            }
                        }

                        if (n + 1 >= CarSection.Groups.Length)
                        {
                            Array.Resize(ref CarSection.Groups, n + 2);
                            CarSection.Groups[n + 1] = new ElementsGroup(ObjectType.Overlay);
                        }

                        ParsePanelAnimatedNode(SectionElement, FileName, TrainPath, Train, Car, CarSection, n + 1);
                    }
                    break;

                case "touch":
                    if (GroupIndex > 0)
                    {
                        Vector3             Position       = Vector3.Zero;
                        Vector3             Size           = Vector3.Zero;
                        int                 JumpScreen     = GroupIndex - 1;
                        List <int>          SoundIndices   = new List <int>();
                        List <CommandEntry> CommandEntries = new List <CommandEntry>();
                        CommandEntry        CommandEntry   = new CommandEntry();

                        foreach (XElement KeyNode in SectionElement.Elements())
                        {
                            string Key        = KeyNode.Name.LocalName;
                            string Value      = KeyNode.Value;
                            int    LineNumber = ((IXmlLineInfo)KeyNode).LineNumber;

                            switch (Key.ToLowerInvariant())
                            {
                            case "position":
                                if (!Vector3.TryParse(KeyNode.Value, ',', out Position))
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, "Position is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;

                            case "size":
                                if (!Vector3.TryParse(KeyNode.Value, ',', out Size))
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, "Size is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;

                            case "jumpscreen":
                                if (Value.Length != 0 && !NumberFormats.TryParseIntVb6(Value, out JumpScreen))
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;

                            case "soundindex":
                                if (Value.Length != 0)
                                {
                                    int SoundIndex;

                                    if (!NumberFormats.TryParseIntVb6(Value, out SoundIndex))
                                    {
                                        Plugin.currentHost.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                    }

                                    SoundIndices.Add(SoundIndex);
                                }
                                break;

                            case "command":
                            {
                                if (!CommandEntries.Contains(CommandEntry))
                                {
                                    CommandEntries.Add(CommandEntry);
                                }

                                if (string.Compare(Value, "N/A", StringComparison.InvariantCultureIgnoreCase) == 0)
                                {
                                    break;
                                }

                                int i;
                                for (i = 0; i < Translations.CommandInfos.Length; i++)
                                {
                                    if (string.Compare(Value, Translations.CommandInfos[i].Name, StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        break;
                                    }
                                }
                                if (i == Translations.CommandInfos.Length || Translations.CommandInfos[i].Type != Translations.CommandType.Digital)
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                else
                                {
                                    CommandEntry.Command = Translations.CommandInfos[i].Command;
                                }
                            }
                            break;

                            case "commandoption":
                                if (!CommandEntries.Contains(CommandEntry))
                                {
                                    CommandEntries.Add(CommandEntry);
                                }

                                if (Value.Length != 0 && !NumberFormats.TryParseIntVb6(Value, out CommandEntry.Option))
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;

                            case "soundentries":
                                if (!KeyNode.HasElements)
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, $"An empty list of touch sound indices was defined at line {((IXmlLineInfo)KeyNode).LineNumber} in XML file {FileName}");
                                    break;
                                }

                                ParseTouchSoundEntryNode(FileName, KeyNode, SoundIndices);
                                break;

                            case "commandentries":
                                if (!KeyNode.HasElements)
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, $"An empty list of touch commands was defined at line {((IXmlLineInfo)KeyNode).LineNumber} in XML file {FileName}");
                                    break;
                                }

                                ParseTouchCommandEntryNode(FileName, KeyNode, CommandEntries);
                                break;
                            }
                        }
                        CreateTouchElement(CarSection.Groups[GroupIndex], Position, Size, JumpScreen, SoundIndices.ToArray(), CommandEntries.ToArray());
                    }
                    break;

                case "include":
                {
                    foreach (XElement KeyNode in SectionElement.Elements())
                    {
                        string Key        = KeyNode.Name.LocalName;
                        string Value      = KeyNode.Value;
                        int    LineNumber = ((IXmlLineInfo)KeyNode).LineNumber;

                        switch (Key.ToLowerInvariant())
                        {
                        case "filename":
                        {
                            string File = OpenBveApi.Path.CombineFile(TrainPath, Value);
                            if (System.IO.File.Exists(File))
                            {
                                System.Text.Encoding e = TextEncoding.GetSystemEncodingFromFile(File);
                                UnifiedObject        currentObject;
                                Plugin.currentHost.LoadObject(File, e, out currentObject);
                                var a = currentObject as AnimatedObjectCollection;
                                if (a != null)
                                {
                                    for (int i = 0; i < a.Objects.Length; i++)
                                    {
                                        Plugin.currentHost.CreateDynamicObject(ref a.Objects[i].internalObject);
                                    }
                                    CarSection.Groups[GroupIndex].Elements = a.Objects;
                                }
                                else
                                {
                                    Plugin.currentHost.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                            }
                        }
                        break;
                        }
                    }
                }
                break;
                }
            }
        }
Beispiel #19
0
        private static void ActionWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            const int progressBufferSize = 5;

            BackgroundWorker worker = (BackgroundWorker)sender;
            WorkerArgs       args   = (WorkerArgs)e.Argument;

            string[] allFiles = Directory.GetFiles(args.BaseDirectory, "*.*",
                                                   args.IncludeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

            WorkerProgress[] progressBuffer = new WorkerProgress[progressBufferSize];
            int reportBufferCounter         = 1;

            IEnumerable <Regex> maskPatterns = GenerateMaskPatterns(args.FileMasks);

            for (int i = 0; i < allFiles.Length; i++)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                string path     = allFiles[i];
                string fileName = Path.GetFileName(path);
                if (!SatisfiesMaskPatterns(fileName, maskPatterns))
                {
                    continue;
                }

                Encoding encoding = TextEncoding.GetFileEncoding(path);
                string   charset  = encoding?.WebName ?? "(Unknown)";

                if (args.Action == CurrentAction.Validate)
                {
                    if (args.ValidCharsets.Contains(charset))
                    {
                        continue;
                    }
                }

                string directoryName = Path.GetDirectoryName(path);

                progressBuffer[reportBufferCounter - 1] = new WorkerProgress
                {
                    Charset       = charset,
                    FileName      = fileName,
                    DirectoryName = directoryName
                };
                reportBufferCounter++;
                if (reportBufferCounter > progressBufferSize)
                {
                    reportBufferCounter = 1;
                    int percentageCompleted         = (i * 100) / allFiles.Length;
                    WorkerProgress[] reportProgress = new WorkerProgress[progressBufferSize];
                    Array.Copy(progressBuffer, reportProgress, progressBufferSize);
                    worker.ReportProgress(percentageCompleted, reportProgress);
                    Array.Clear(progressBuffer, 0, progressBufferSize);
                }
            }

            // Copy remaining results from buffer, if any.
            if (reportBufferCounter > 1)
            {
                reportBufferCounter--;
                int percentageCompleted         = 100;
                WorkerProgress[] reportProgress = new WorkerProgress[reportBufferCounter];
                Array.Copy(progressBuffer, reportProgress, reportBufferCounter);
                worker.ReportProgress(percentageCompleted, reportProgress);
                Array.Clear(progressBuffer, 0, reportBufferCounter);
            }
        }
        private void OnComplete(NativeActivityContext context, ActivityInstance completedInstance, IEncryption result)
        {
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var input    = Input.Get(context);
            var colsLen  = input.Columns.Count;
            var encoding = TextEncoding.Get(context);
            var pass     = GetRawKey(context);

            var sortBy  = Sort.Get(context);
            var columns = DataTableUtil.IdentifyDataColumns(input, Columns?.Get(context), Enumerable.Range(0, colsLen)).ToList();

            Func <string, string> action;

            if (Action == CryptoActions.Encrypt)
            {
                action = (string value) => Convert.ToBase64String(result.Encrypt(encoding.GetBytes(value), encoding.GetBytes(pass)));
            }
            else
            {
                action = (string value) => encoding.GetString(result.Decrypt(Convert.FromBase64String(value), encoding.GetBytes(pass)));
            }

            var rows   = input.AsEnumerable();
            var values = new List <object[]>();

            void Add(DataRow row)
            {
                values.Add(ApplyTo(row, colsLen, columns, action));
            }

            if (ParallelProcessing)
            {
                Parallel.ForEach(rows, Add);
            }
            else
            {
                foreach (DataRow row in input.Rows)
                {
                    Add(row);
                }
            }

            var output = CreateCryptoDataTable(input, columns);

            output.BeginLoadData();

            foreach (var value in values)
            {
                output.LoadDataRow(value, false);
            }

            output.AcceptChanges();
            output.EndLoadData();

            if (!string.IsNullOrWhiteSpace(sortBy))
            {
                output.DefaultView.Sort = sortBy;
                output = output.DefaultView.ToTable();
            }

            Result.Set(context, output);
        }
Beispiel #21
0
 public Tuple <int, HttpMessage> Parse(string text, bool useFullText = false)
 {
     return(Parse(TextEncoding.GetBytes(text), useFullText));
 }
Beispiel #22
0
 /// <summary>
 /// Send message text to specific client in asynchronous mode with default encoding, see TextEncoding property.
 /// </summary>
 /// <param name="clientID">The id of the client to receive messsage.</param>
 /// <param name="text">The message text to be sent.</param>
 /// <param name="callback">The callback that will be called after sending operation.</param>
 /// <returns>An System.IAsyncResult that references the asynchronous send.</returns>
 public IAsyncResult SendTextAsync(long clientID, string text, AsyncCallback callback)
 {
     return(SendMessageAsync(clientID, TextEncoding.GetBytes(text), callback));
 }
Beispiel #23
0
 public static string ByteArrayToString(byte[] bytes, TextEncoding encoding) => GetEncoder(encoding).GetString(bytes);
Beispiel #24
0
 /// <summary>
 /// Send message text to specific group collection in asynchronous mode with default encoding, see TextEncoding property.
 /// </summary>
 /// <param name="groupNameCollection">The group collection to receive the message.</param>
 /// <param name="text">The message text to be sent.</param>
 public void SendGroupTextAsync(IEnumerable <string> groupNameCollection, string text)
 {
     SendGroupMessageAsync(groupNameCollection, TextEncoding.GetBytes(text));
 }
Beispiel #25
0
 public static byte[] StringToByteArray(string s, TextEncoding encoding) => GetEncoder(encoding).GetBytes(s);
        public static Stream CreateBody(this FormDataSet formDataSet, String enctype, String charset)
        {
            var encoding = TextEncoding.Resolve(charset);

            return(formDataSet.CreateBody(enctype, encoding));
        }
Beispiel #27
0
 internal void WriteChars(char[] chars, int offset, int len)
 {
     Debug.Assert(TextEncoding.GetByteCount(chars) <= WriteSpaceLeft);
     _writePosition += TextEncoding.GetBytes(chars, offset, len == 0 ? chars.Length : len, _buf, _writePosition);
 }
Beispiel #28
0
        // Operations


        /// <summary>
        /// Append ASCII string to buffer
        /// </summary>
        /// <param name='text'>
        /// Text.
        /// </param>
        public void Append(string text)
        {
            byte[] bytes = TextEncoding.GetBytes(text);
            Append(bytes, 0, bytes.Length);
        }
Beispiel #29
0
        internal static void Parse(string fileName, out Sound sound)
        {
            sound = new Sound();

            CultureInfo   culture  = CultureInfo.InvariantCulture;
            List <string> lines    = File.ReadAllLines(fileName, TextEncoding.GetSystemEncodingFromFile(fileName)).ToList();
            string        basePath = System.IO.Path.GetDirectoryName(fileName);

            for (int i = lines.Count - 1; i >= 0; i--)
            {
                /*
                 * Strip comments and remove empty resulting lines etc.
                 *
                 * This fixes an error with some NYCTA content, which has
                 * a copyright notice instead of the file header specified....
                 */
                int j = lines[i].IndexOf(';');

                if (j >= 0)
                {
                    lines[i] = lines[i].Substring(0, j).Trim();
                }
                else
                {
                    lines[i] = lines[i].Trim();
                }

                if (string.IsNullOrEmpty(lines[i]))
                {
                    lines.RemoveAt(i);
                }
            }

            if (!lines.Any())
            {
                Interface.AddMessage(MessageType.Error, false, $"Empty sound.cfg encountered in {fileName}.");
            }

            if (string.Compare(lines[0], "version 1.0", StringComparison.OrdinalIgnoreCase) != 0)
            {
                Interface.AddMessage(MessageType.Error, false, $"Invalid file format encountered in {fileName}. The first line is expected to be \"Version 1.0\".");
            }

            for (int i = 0; i < lines.Count; i++)
            {
                switch (lines[i].ToLowerInvariant())
                {
                case "[run]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();
                            int    k;

                            if (!int.TryParse(a, NumberStyles.Integer, culture, out k))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"Invalid index appeared at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                if (k >= 0)
                                {
                                    sound.SoundElements.Add(new RunElement {
                                        Key = k, FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Error, false, $"Index must be greater or equal to zero at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[flange]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();
                            int    k;

                            if (!int.TryParse(a, NumberStyles.Integer, culture, out k))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"Invalid index appeared at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                if (k >= 0)
                                {
                                    sound.SoundElements.Add(new FlangeElement {
                                        Key = k, FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Error, false, $"Index must be greater or equal to zero at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[motor]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();
                            int    k;

                            if (!int.TryParse(a, NumberStyles.Integer, culture, out k))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"Invalid index appeared at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                if (k >= 0)
                                {
                                    sound.SoundElements.Add(new MotorElement {
                                        Key = k, FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Error, false, $"Index is invalid at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[switch]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();
                            int    k;

                            if (!int.TryParse(a, NumberStyles.Integer, culture, out k))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"Invalid index appeared at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                if (k >= 0)
                                {
                                    sound.SoundElements.Add(new FrontSwitchElement {
                                        Key = k, FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Error, false, $"Index is invalid at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[brake]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                BrakeKey[] keys = Enum.GetValues(typeof(BrakeKey)).OfType <BrakeKey>().Where(x => x.GetStringValues().Any(y => y.Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (keys.Any())
                                {
                                    sound.SoundElements.Add(new BrakeElement {
                                        Key = keys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[compressor]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                CompressorKey[] keys = Enum.GetValues(typeof(CompressorKey)).OfType <CompressorKey>().Where(x => x.GetStringValues().Any(y => y.Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (keys.Any())
                                {
                                    sound.SoundElements.Add(new CompressorElement {
                                        Key = keys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[suspension]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                SuspensionKey[] keys = Enum.GetValues(typeof(SuspensionKey)).OfType <SuspensionKey>().Where(x => x.GetStringValues().Any(y => y.Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (keys.Any())
                                {
                                    sound.SoundElements.Add(new SuspensionElement {
                                        Key = keys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[horn]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                HornKey[] primaryKeys   = Enum.GetValues(typeof(HornKey)).OfType <HornKey>().Where(x => x.GetStringValues().Any(y => $"Primary{y}".Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();
                                HornKey[] secondaryKeys = Enum.GetValues(typeof(HornKey)).OfType <HornKey>().Where(x => x.GetStringValues().Any(y => $"Secondary{y}".Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();
                                HornKey[] musicKeys     = Enum.GetValues(typeof(HornKey)).OfType <HornKey>().Where(x => x.GetStringValues().Any(y => $"Music{y}".Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (primaryKeys.Any())
                                {
                                    sound.SoundElements.Add(new PrimaryHornElement {
                                        Key = primaryKeys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else if (secondaryKeys.Any())
                                {
                                    sound.SoundElements.Add(new SecondaryHornElement {
                                        Key = secondaryKeys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else if (musicKeys.Any())
                                {
                                    sound.SoundElements.Add(new MusicHornElement {
                                        Key = musicKeys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else if ("Primary".Equals(a, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    sound.SoundElements.Add(new PrimaryHornElement {
                                        Key = HornKey.Loop, FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else if ("Secondary".Equals(a, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    sound.SoundElements.Add(new SecondaryHornElement {
                                        Key = HornKey.Loop, FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else if ("Music".Equals(a, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    sound.SoundElements.Add(new MusicHornElement {
                                        Key = HornKey.Loop, FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[door]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                DoorKey[] keys = Enum.GetValues(typeof(DoorKey)).OfType <DoorKey>().Where(x => x.GetStringValues().Any(y => y.Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (keys.Any())
                                {
                                    sound.SoundElements.Add(new DoorElement {
                                        Key = keys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[ats]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                int k;

                                if (!int.TryParse(a, NumberStyles.Integer, culture, out k))
                                {
                                    Interface.AddMessage(MessageType.Error, false, $"Invalid index appeared at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                                else
                                {
                                    if (k >= 0)
                                    {
                                        sound.SoundElements.Add(new AtsElement {
                                            Key = k, FilePath = Path.CombineFile(basePath, b)
                                        });
                                    }
                                    else
                                    {
                                        Interface.AddMessage(MessageType.Warning, false, "Index must be greater or equal to zero at line " + (i + 1).ToString(culture) + " in file " + fileName);
                                    }
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[buzzer]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                BuzzerKey[] keys = Enum.GetValues(typeof(BuzzerKey)).OfType <BuzzerKey>().Where(x => x.GetStringValues().Any(y => y.Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (keys.Any())
                                {
                                    sound.SoundElements.Add(new BuzzerElement {
                                        Key = keys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[pilot lamp]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                PilotLampKey[] keys = Enum.GetValues(typeof(PilotLampKey)).OfType <PilotLampKey>().Where(x => x.GetStringValues().Any(y => y.Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (keys.Any())
                                {
                                    sound.SoundElements.Add(new PilotLampElement {
                                        Key = keys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[brake handle]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                BrakeHandleKey[] keys = Enum.GetValues(typeof(BrakeHandleKey)).OfType <BrakeHandleKey>().Where(x => x.GetStringValues().Any(y => y.Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (keys.Any())
                                {
                                    sound.SoundElements.Add(new BrakeHandleElement {
                                        Key = keys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[master controller]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                MasterControllerKey[] keys = Enum.GetValues(typeof(MasterControllerKey)).OfType <MasterControllerKey>().Where(x => x.GetStringValues().Any(y => y.Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (keys.Any())
                                {
                                    sound.SoundElements.Add(new MasterControllerElement {
                                        Key = keys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[reverser]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                ReverserKey[] keys = Enum.GetValues(typeof(ReverserKey)).OfType <ReverserKey>().Where(x => x.GetStringValues().Any(y => y.Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (keys.Any())
                                {
                                    sound.SoundElements.Add(new ReverserElement {
                                        Key = keys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[breaker]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                BreakerKey[] keys = Enum.GetValues(typeof(BreakerKey)).OfType <BreakerKey>().Where(x => x.GetStringValues().Any(y => y.Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (keys.Any())
                                {
                                    sound.SoundElements.Add(new BreakerElement {
                                        Key = keys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[others]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                OthersKey[] keys = Enum.GetValues(typeof(OthersKey)).OfType <OthersKey>().Where(x => x.GetStringValues().Any(y => y.Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (keys.Any())
                                {
                                    sound.SoundElements.Add(new OthersElement {
                                        Key = keys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[requeststop]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                RequestStopKey[] keys = Enum.GetValues(typeof(RequestStopKey)).OfType <RequestStopKey>().Where(x => x.GetStringValues().Any(y => y.Equals(a, StringComparison.InvariantCultureIgnoreCase))).ToArray();

                                if (keys.Any())
                                {
                                    sound.SoundElements.Add(new RequestStopElement {
                                        Key = keys.First(), FilePath = Path.CombineFile(basePath, b)
                                    });
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Warning, false, $"Unsupported key {a} encountered at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;

                case "[touch]":
                    i++;

                    while (i < lines.Count && !lines[i].StartsWith("[", StringComparison.Ordinal))
                    {
                        int j = lines[i].IndexOf("=", StringComparison.Ordinal);

                        if (j >= 0)
                        {
                            string a = lines[i].Substring(0, j).TrimEnd();
                            string b = lines[i].Substring(j + 1).TrimStart();

                            if (b.Length == 0 || Path.ContainsInvalidChars(b))
                            {
                                Interface.AddMessage(MessageType.Error, false, $"FileName contains illegal characters or is empty at line {(i + 1).ToString(culture)} in file {fileName}");
                            }
                            else
                            {
                                int k;

                                if (!int.TryParse(a, NumberStyles.Integer, culture, out k))
                                {
                                    Interface.AddMessage(MessageType.Error, false, $"Invalid index appeared at line {(i + 1).ToString(culture)} in file {fileName}");
                                }
                                else
                                {
                                    if (k >= 0)
                                    {
                                        sound.SoundElements.Add(new TouchElement {
                                            Key = k, FilePath = Path.CombineFile(basePath, b)
                                        });
                                    }
                                    else
                                    {
                                        Interface.AddMessage(MessageType.Warning, false, "Index must be greater or equal to zero at line " + (i + 1).ToString(culture) + " in file " + fileName);
                                    }
                                }
                            }
                        }

                        i++;
                    }

                    i--;
                    break;
                }
            }

            sound.SoundElements = new ObservableCollection <SoundElement>(sound.SoundElements.GroupBy(x => new { Type = x.GetType(), x.Key }).Select(x => x.First()));
        }
Beispiel #30
0
        /// <summary>
        /// Encodes the body of a <c>HeartbeatMessage</c> object into the target byte array.
        /// </summary>
        /// <param name="target">the target byte array.</param>
        /// <param name="offset">the position to start writing.</param>
        /// <returns>The number of bytes written into <c>bytes</c>.</returns>
        protected override int GetBodyBytes(byte[] target, int offset)
        {
            string body = m_username;

            return(TextEncoding.GetBytes(body, 0, body.Length, target, offset));
        }
Beispiel #31
0
        public static Stream CreateBody(this FormDataSet formDataSet, String enctype, String?charset, IHtmlEncoder?htmlEncoder)
        {
            var encoding = TextEncoding.Resolve(charset);

            return(formDataSet.CreateBody(enctype, encoding, htmlEncoder ?? new DefaultHtmlEncoder()));
        }
Beispiel #32
0
        /// <summary>This function processes the list of expressions for $Char, $Rnd, $If and $Sub directives, and evaluates them into the final expressions dataset</summary>
        private void PreprocessChrRndSub(string FileName, System.Text.Encoding Encoding, ref Expression[] Expressions)
        {
            string[] Subs    = new string[16];
            int      openIfs = 0;

            for (int i = 0; i < Expressions.Length; i++)
            {
                string Epilog = " at line " + Expressions[i].Line.ToString(Culture) + ", column " + Expressions[i].Column.ToString(Culture) + " in file " + Expressions[i].File;
                bool   continueWithNextExpression = false;
                for (int j = Expressions[i].Text.Length - 1; j >= 0; j--)
                {
                    if (Expressions[i].Text[j] == '$')
                    {
                        int k;
                        for (k = j + 1; k < Expressions[i].Text.Length; k++)
                        {
                            if (Expressions[i].Text[k] == '(')
                            {
                                break;
                            }
                            else if (Expressions[i].Text[k] == '/' | Expressions[i].Text[k] == '\\')
                            {
                                k = Expressions[i].Text.Length + 1;
                                break;
                            }
                        }
                        if (k <= Expressions[i].Text.Length)
                        {
                            string t = Expressions[i].Text.Substring(j, k - j).TrimEnd(new char[] { });
                            int    l = 1, h;
                            for (h = k + 1; h < Expressions[i].Text.Length; h++)
                            {
                                switch (Expressions[i].Text[h])
                                {
                                case '(':
                                    l++;
                                    break;

                                case ')':
                                    l--;
                                    if (l < 0)
                                    {
                                        continueWithNextExpression = true;
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Invalid parenthesis structure in " + t + Epilog);
                                    }
                                    break;
                                }
                                if (l <= 0)
                                {
                                    break;
                                }
                            }
                            if (continueWithNextExpression)
                            {
                                break;
                            }
                            if (l != 0)
                            {
                                Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Invalid parenthesis structure in " + t + Epilog);
                                break;
                            }
                            string s = Expressions[i].Text.Substring(k + 1, h - k - 1).Trim(new char[] { });
                            switch (t.ToLowerInvariant())
                            {
                            case "$if":
                                if (j != 0)
                                {
                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "The $If directive must not appear within another statement" + Epilog);
                                }
                                else
                                {
                                    double num;
                                    if (double.TryParse(s, NumberStyles.Float, Culture, out num))
                                    {
                                        openIfs++;
                                        Expressions[i].Text = string.Empty;
                                        if (num == 0.0)
                                        {
                                            /*
                                             * Blank every expression until the matching $Else or $EndIf
                                             * */
                                            i++;
                                            int level = 1;
                                            while (i < Expressions.Length)
                                            {
                                                if (Expressions[i].Text.StartsWith("$if", StringComparison.OrdinalIgnoreCase))
                                                {
                                                    Expressions[i].Text = string.Empty;
                                                    level++;
                                                }
                                                else if (Expressions[i].Text.StartsWith("$else", StringComparison.OrdinalIgnoreCase))
                                                {
                                                    Expressions[i].Text = string.Empty;
                                                    if (level == 1)
                                                    {
                                                        level--;
                                                        break;
                                                    }
                                                }
                                                else if (Expressions[i].Text.StartsWith("$endif", StringComparison.OrdinalIgnoreCase))
                                                {
                                                    Expressions[i].Text = string.Empty;
                                                    level--;
                                                    if (level == 0)
                                                    {
                                                        openIfs--;
                                                        break;
                                                    }
                                                }
                                                else
                                                {
                                                    Expressions[i].Text = string.Empty;
                                                }
                                                i++;
                                            }
                                            if (level != 0)
                                            {
                                                Plugin.CurrentHost.AddMessage(MessageType.Error, false, "$EndIf missing at the end of the file" + Epilog);
                                            }
                                        }
                                        continueWithNextExpression = true;
                                        break;
                                    }
                                    else
                                    {
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "The $If condition does not evaluate to a number" + Epilog);
                                    }
                                }
                                continueWithNextExpression = true;
                                break;

                            case "$else":
                                /*
                                 * Blank every expression until the matching $EndIf
                                 * */
                                Expressions[i].Text = string.Empty;
                                if (openIfs != 0)
                                {
                                    i++;
                                    int level = 1;
                                    while (i < Expressions.Length)
                                    {
                                        if (Expressions[i].Text.StartsWith("$if", StringComparison.OrdinalIgnoreCase))
                                        {
                                            Expressions[i].Text = string.Empty;
                                            level++;
                                        }
                                        else if (Expressions[i].Text.StartsWith("$else", StringComparison.OrdinalIgnoreCase))
                                        {
                                            Expressions[i].Text = string.Empty;
                                            if (level == 1)
                                            {
                                                Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Duplicate $Else encountered" + Epilog);
                                            }
                                        }
                                        else if (Expressions[i].Text.StartsWith("$endif", StringComparison.OrdinalIgnoreCase))
                                        {
                                            Expressions[i].Text = string.Empty;
                                            level--;
                                            if (level == 0)
                                            {
                                                openIfs--;
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            Expressions[i].Text = string.Empty;
                                        }
                                        i++;
                                    }
                                    if (level != 0)
                                    {
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "$EndIf missing at the end of the file" + Epilog);
                                    }
                                }
                                else
                                {
                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "$Else without matching $If encountered" + Epilog);
                                }
                                continueWithNextExpression = true;
                                break;

                            case "$endif":
                                Expressions[i].Text = string.Empty;
                                if (openIfs != 0)
                                {
                                    openIfs--;
                                }
                                else
                                {
                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "$EndIf without matching $If encountered" + Epilog);
                                }
                                continueWithNextExpression = true;
                                break;

                            case "$include":
                                if (j != 0)
                                {
                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "The $Include directive must not appear within another statement" + Epilog);
                                    continueWithNextExpression = true;
                                    break;
                                }
                                string[] args = s.Split(new char[] { ';' });
                                for (int ia = 0; ia < args.Length; ia++)
                                {
                                    args[ia] = args[ia].Trim(new char[] { });
                                }
                                int      count        = (args.Length + 1) / 2;
                                string[] files        = new string[count];
                                double[] weights      = new double[count];
                                double[] offsets      = new double[count];
                                double   weightsTotal = 0.0;
                                for (int ia = 0; ia < count; ia++)
                                {
                                    string file;
                                    double offset;
                                    int    colon = args[2 * ia].IndexOf(':');
                                    if (colon >= 0)
                                    {
                                        file = args[2 * ia].Substring(0, colon).TrimEnd(new char[] { });
                                        string value = args[2 * ia].Substring(colon + 1).TrimStart(new char[] { });
                                        if (!double.TryParse(value, NumberStyles.Float, Culture, out offset))
                                        {
                                            continueWithNextExpression = true;
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "The track position offset " + value + " is invalid in " + t + Epilog);
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        file   = args[2 * ia];
                                        offset = 0.0;
                                    }
                                    files[ia]   = Path.CombineFile(System.IO.Path.GetDirectoryName(FileName), file);
                                    offsets[ia] = offset;
                                    if (!System.IO.File.Exists(files[ia]))
                                    {
                                        continueWithNextExpression = true;
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "The file " + file + " could not be found in " + t + Epilog);
                                        for (int ta = i; ta < Expressions.Length - 1; ta++)
                                        {
                                            Expressions[ta] = Expressions[ta + 1];
                                        }
                                        Array.Resize(ref Expressions, Expressions.Length - 1);
                                        i--;
                                        break;
                                    }
                                    if (2 * ia + 1 < args.Length)
                                    {
                                        if (!NumberFormats.TryParseDoubleVb6(args[2 * ia + 1], out weights[ia]))
                                        {
                                            continueWithNextExpression = true;
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "A weight is invalid in " + t + Epilog);
                                            break;
                                        }
                                        if (weights[ia] <= 0.0)
                                        {
                                            continueWithNextExpression = true;
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "A weight is not positive in " + t + Epilog);
                                            break;
                                        }
                                        weightsTotal += weights[ia];
                                    }
                                    else
                                    {
                                        weights[ia]   = 1.0;
                                        weightsTotal += 1.0;
                                    }
                                }
                                if (count == 0)
                                {
                                    continueWithNextExpression = true;
                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "No file was specified in " + t + Epilog);
                                    break;
                                }
                                if (!continueWithNextExpression)
                                {
                                    double number      = Plugin.RandomNumberGenerator.NextDouble() * weightsTotal;
                                    double value       = 0.0;
                                    int    chosenIndex = 0;
                                    for (int ia = 0; ia < count; ia++)
                                    {
                                        value += weights[ia];
                                        if (value > number)
                                        {
                                            chosenIndex = ia;
                                            break;
                                        }
                                    }
                                    Expression[] expr;
                                    //Get the text encoding of our $Include file
                                    System.Text.Encoding includeEncoding = TextEncoding.GetSystemEncodingFromFile(files[chosenIndex]);
                                    if (!includeEncoding.Equals(Encoding) && includeEncoding.WindowsCodePage != Encoding.WindowsCodePage)
                                    {
                                        //If the encodings do not match, add a warning
                                        //This is not critical, but it's a bad idea to mix and match character encodings within a routefile, as the auto-detection may sometimes be wrong
                                        Plugin.CurrentHost.AddMessage(MessageType.Warning, false, "The text encoding of the $Include file " + files[chosenIndex] + " does not match that of the base routefile.");
                                    }
                                    string[] lines = System.IO.File.ReadAllLines(files[chosenIndex], includeEncoding);
                                    PreprocessSplitIntoExpressions(files[chosenIndex], lines, out expr, false, offsets[chosenIndex] + Expressions[i].TrackPositionOffset);
                                    int length = Expressions.Length;
                                    if (expr.Length == 0)
                                    {
                                        for (int ia = i; ia < Expressions.Length - 1; ia++)
                                        {
                                            Expressions[ia] = Expressions[ia + 1];
                                        }
                                        Array.Resize(ref Expressions, length - 1);
                                    }
                                    else
                                    {
                                        Array.Resize(ref Expressions, length + expr.Length - 1);
                                        for (int ia = Expressions.Length - 1; ia >= i + expr.Length; ia--)
                                        {
                                            Expressions[ia] = Expressions[ia - expr.Length + 1];
                                        }
                                        for (int ia = 0; ia < expr.Length; ia++)
                                        {
                                            Expressions[i + ia] = expr[ia];
                                        }
                                    }
                                    i--;
                                    continueWithNextExpression = true;
                                }
                                break;

                            case "$chr":
                            case "$chruni":
                            {
                                int x;
                                if (NumberFormats.TryParseIntVb6(s, out x))
                                {
                                    if (x < 0)
                                    {
                                        //Must be non-negative
                                        continueWithNextExpression = true;
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Index must be a non-negative character in " + t + Epilog);
                                    }
                                    else
                                    {
                                        Expressions[i].Text = Expressions[i].Text.Substring(0, j) + char.ConvertFromUtf32(x) + Expressions[i].Text.Substring(h + 1);
                                    }
                                }
                                else
                                {
                                    continueWithNextExpression = true;
                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Index is invalid in " + t + Epilog);
                                }
                            } break;

                            case "$chrascii":
                            {
                                int x;
                                if (NumberFormats.TryParseIntVb6(s, out x))
                                {
                                    if (x < 0 || x > 127)
                                    {
                                        //Standard ASCII characters from 0-127
                                        continueWithNextExpression = true;
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Index does not correspond to a valid ASCII character in " + t + Epilog);
                                    }
                                    else
                                    {
                                        Expressions[i].Text = Expressions[i].Text.Substring(0, j) + char.ConvertFromUtf32(x) + Expressions[i].Text.Substring(h + 1);
                                    }
                                }
                                else
                                {
                                    continueWithNextExpression = true;
                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Index is invalid in " + t + Epilog);
                                }
                            }
                            break;

                            case "$rnd":
                            {
                                int m = s.IndexOf(";", StringComparison.Ordinal);
                                if (m >= 0)
                                {
                                    string s1 = s.Substring(0, m).TrimEnd(new char[] { });
                                    string s2 = s.Substring(m + 1).TrimStart(new char[] { });
                                    int    x; if (NumberFormats.TryParseIntVb6(s1, out x))
                                    {
                                        int y; if (NumberFormats.TryParseIntVb6(s2, out y))
                                        {
                                            int z = x + (int)Math.Floor(Plugin.RandomNumberGenerator.NextDouble() * (y - x + 1));
                                            Expressions[i].Text = Expressions[i].Text.Substring(0, j) + z.ToString(Culture) + Expressions[i].Text.Substring(h + 1);
                                        }
                                        else
                                        {
                                            continueWithNextExpression = true;
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Index2 is invalid in " + t + Epilog);
                                        }
                                    }
                                    else
                                    {
                                        continueWithNextExpression = true;
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Index1 is invalid in " + t + Epilog);
                                    }
                                }
                                else
                                {
                                    continueWithNextExpression = true;
                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Two arguments are expected in " + t + Epilog);
                                }
                            } break;

                            case "$sub":
                            {
                                l = 0;
                                bool f = false;
                                int  m;
                                for (m = h + 1; m < Expressions[i].Text.Length; m++)
                                {
                                    switch (Expressions[i].Text[m])
                                    {
                                    case '(': l++; break;

                                    case ')': l--; break;

                                    case '=':
                                        if (l == 0)
                                        {
                                            f = true;
                                        }
                                        break;

                                    default:
                                        if (!char.IsWhiteSpace(Expressions[i].Text[m]))
                                        {
                                            l = -1;
                                        }
                                        break;
                                    }
                                    if (f | l < 0)
                                    {
                                        break;
                                    }
                                }
                                if (f)
                                {
                                    l = 0;
                                    int n;
                                    for (n = m + 1; n < Expressions[i].Text.Length; n++)
                                    {
                                        switch (Expressions[i].Text[n])
                                        {
                                        case '(': l++; break;

                                        case ')': l--; break;
                                        }
                                        if (l < 0)
                                        {
                                            break;
                                        }
                                    }
                                    int x;
                                    if (NumberFormats.TryParseIntVb6(s, out x))
                                    {
                                        if (x >= 0)
                                        {
                                            while (x >= Subs.Length)
                                            {
                                                Array.Resize(ref Subs, Subs.Length << 1);
                                            }
                                            Subs[x]             = Expressions[i].Text.Substring(m + 1, n - m - 1).Trim(new char[] { });
                                            Expressions[i].Text = Expressions[i].Text.Substring(0, j) + Expressions[i].Text.Substring(n);
                                        }
                                        else
                                        {
                                            continueWithNextExpression = true;
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Index is expected to be non-negative in " + t + Epilog);
                                        }
                                    }
                                    else
                                    {
                                        continueWithNextExpression = true;
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Index is invalid in " + t + Epilog);
                                    }
                                }
                                else
                                {
                                    int x;
                                    if (NumberFormats.TryParseIntVb6(s, out x))
                                    {
                                        if (x >= 0 & x < Subs.Length && Subs[x] != null)
                                        {
                                            Expressions[i].Text = Expressions[i].Text.Substring(0, j) + Subs[x] + Expressions[i].Text.Substring(h + 1);
                                        }
                                        else
                                        {
                                            continueWithNextExpression = true;
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Index is out of range in " + t + Epilog);
                                        }
                                    }
                                    else
                                    {
                                        continueWithNextExpression = true;
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Index is invalid in " + t + Epilog);
                                    }
                                }
                            }
                            break;
                            }
                        }
                    }
                    if (continueWithNextExpression)
                    {
                        break;
                    }
                }
            }
            // handle comments introduced via chr, rnd, sub
            {
                int length = Expressions.Length;
                for (int i = 0; i < length; i++)
                {
                    Expressions[i].Text = Expressions[i].Text.Trim(new char[] { });
                    if (Expressions[i].Text.Length != 0)
                    {
                        if (Expressions[i].Text[0] == ';')
                        {
                            for (int j = i; j < length - 1; j++)
                            {
                                Expressions[j] = Expressions[j + 1];
                            }
                            length--;
                            i--;
                        }
                    }
                    else
                    {
                        for (int j = i; j < length - 1; j++)
                        {
                            Expressions[j] = Expressions[j + 1];
                        }
                        length--;
                        i--;
                    }
                }
                if (length != Expressions.Length)
                {
                    Array.Resize(ref Expressions, length);
                }
            }
        }
Beispiel #33
0
        internal void WriteStringSimple(string s)
        {
            Contract.Requires(TextEncoding.GetByteCount(s) <= WriteSpaceLeft);

            WritePosition += TextEncoding.GetBytes(s, 0, s.Length, _buf, WritePosition);
        }
 static bool TryWriteString(string s, Span<byte> buffer, TextEncoding encoding, ref int bytesWritten)
 {
     int written;
     if (!s.TryEncode(buffer.Slice(bytesWritten), out written, encoding))
     {
         bytesWritten = 0;
         return false;
     }
     bytesWritten += written;
     return true;
 }
Beispiel #35
0
        public static void ProcessFile(string pathIn, string pathOut, ConvertOption option, LogHandler callback)
        {
            callback(Message.FileStarted, pathIn);
            UnifiedObject unifiedObj = null;

            callback(Message.Reading);
            PluginManager.logHandler = callback;
            Encoding encoding          = option.UseLocalEncoding ? Encoding.Default : TextEncoding.GetSystemEncodingFromFile(pathIn);
            bool     isSketchupObjFile = IsSketchupObjFile(pathIn, encoding);

            if (PluginManager.LoadObject(pathIn, encoding, out unifiedObj))
            {
                var staticObj = unifiedObj as StaticObject;

                callback(Message.OptimizingObject);
                staticObj.OptimizeObject(false, 0, true);

                callback(Message.OptimizingMaterial);
                OptimizeMaterial(ref staticObj.Mesh);

                callback(Message.PostProcessing);
                if (isSketchupObjFile)
                {
                    callback(Message.SketchupHack);
                    option.Mirror.Z ^= true;
                }
                if (option.Mirror != default(Bool3))
                {
                    staticObj.ApplyMirror(option.Mirror.X, option.Mirror.Y, option.Mirror.Z,
                                          option.Mirror.X, option.Mirror.Y, option.Mirror.Z);
                }
                if (option.Scale != default(Vector3) && option.Scale != new Vector3(1, 1, 1))
                {
                    staticObj.ApplyScale(option.Scale.X, option.Scale.Y, option.Scale.Z);
                }
                if (option.Rotation != default(Vector3))
                {
                    // TODO: This doesn't seem to be the correct way to apply euler angle rotation!
                    if (option.Rotation.X != 0.0)
                    {
                        staticObj.ApplyRotation(new Vector3(1, 0, 0), option.Rotation.X);
                    }
                    if (option.Rotation.Y != 0.0)
                    {
                        staticObj.ApplyRotation(new Vector3(0, 1, 0), option.Rotation.X);
                    }
                    if (option.Rotation.Z != 0.0)
                    {
                        staticObj.ApplyRotation(new Vector3(0, 0, 1), option.Rotation.X);
                    }
                }
                if (option.Translation != default(Vector3))
                {
                    staticObj.ApplyTranslation(option.Translation.X, option.Translation.Y, option.Translation.Z);
                }
                //var dimension = "[" + string.Join(", ", staticObj.Mesh.BoundingBox.Select(v => string.Format("({0}, {1}, {2})", v.X, v.Y, v.Z))) + "]";
                //callback(Message.Dimension, dimension);

                if (pathOut.EndsWith(".csv", StringComparison.OrdinalIgnoreCase))
                {
                    callback(Message.Writing);
                    CsvWriter.Save(staticObj, pathOut, option, callback);
                }
                else if (pathOut.EndsWith(".hmmo", StringComparison.OrdinalIgnoreCase))
                {
                    callback(Message.PostProcessing);
                    staticObj.Mesh.Faces = Triangulate(staticObj.Mesh.Faces);
                    callback(Message.Writing);
                    // TODO: Hmmo Writer
                }
            }
            else
            {
                callback(Message.ObjectNotReadable);
            }
            callback(Message.FileDone, pathOut);
        }
        string GenerateOptions(DotNetProjectConfiguration configuration, VBCompilerParameters compilerparameters, VBProjectParameters projectparameters, string outputFileName)
        {
            DotNetProject project = (DotNetProject)configuration.ParentItem;
            StringBuilder sb      = new StringBuilder();

            sb.AppendFormat("\"-out:{0}\"", outputFileName);
            sb.AppendLine();

            sb.AppendLine("-nologo");
            sb.AppendLine("-utf8output");
            sb.AppendLine("-quiet");

            sb.AppendFormat("-debug:{0}", compilerparameters.DebugType);
            sb.AppendLine();

            if (compilerparameters.Optimize)
            {
                sb.AppendLine("-optimize+");
            }


            if (projectparameters.OptionStrict)
            {
                sb.AppendLine("-optionstrict+");
            }
            else
            {
                sb.AppendLine("-optionstrict-");
            }

            if (projectparameters.OptionExplicit)
            {
                sb.AppendLine("-optionexplicit+");
            }
            else
            {
                sb.AppendLine("-optionexplicit-");
            }

            if (projectparameters.BinaryOptionCompare)
            {
                sb.AppendLine("-optioncompare:binary");
            }
            else
            {
                sb.AppendLine("-optioncompare:text");
            }

            if (projectparameters.OptionInfer)
            {
                sb.AppendLine("-optioninfer+");
            }
            else
            {
                sb.AppendLine("-optioninfer-");
            }

            string mytype = projectparameters.MyType;

            if (!string.IsNullOrEmpty(mytype))
            {
                sb.AppendFormat("-define:_MYTYPE=\\\"{0}\\\"", mytype);
                sb.AppendLine();
            }

            string win32IconPath = projectparameters.ApplicationIcon;

            if (!string.IsNullOrEmpty(win32IconPath) && File.Exists(win32IconPath))
            {
                sb.AppendFormat("\"-win32icon:{0}\"", win32IconPath);
                sb.AppendLine();
            }

            if (!string.IsNullOrEmpty(projectparameters.CodePage))
            {
                TextEncoding enc = TextEncoding.GetEncoding(projectparameters.CodePage);
                sb.AppendFormat("-codepage:{0}", enc.CodePage);
                sb.AppendLine();
            }

            if (!string.IsNullOrEmpty(project.DefaultNamespace))
            {
                sb.AppendFormat("-rootnamespace:{0}", project.DefaultNamespace);
                sb.AppendLine();
            }

            if (!string.IsNullOrEmpty(compilerparameters.DefineConstants))
            {
                sb.AppendFormat("\"-define:{0}\"", compilerparameters.DefineConstants);
                sb.AppendLine();
            }

            if (compilerparameters.DefineDebug)
            {
                sb.AppendLine("-define:DEBUG=-1");
            }

            if (compilerparameters.DefineTrace)
            {
                sb.AppendLine("-define:TRACE=-1");
            }

            if (compilerparameters.WarningsDisabled)
            {
                sb.AppendLine("-nowarn");
            }
            else if (!string.IsNullOrEmpty(compilerparameters.NoWarn))
            {
                sb.AppendFormat("-nowarn:{0}", compilerparameters.NoWarn);
                sb.AppendLine();
            }

            if (!string.IsNullOrEmpty(compilerparameters.WarningsAsErrors))
            {
                sb.AppendFormat("-warnaserror+:{0}", compilerparameters.WarningsAsErrors);
                sb.AppendLine();
            }

            if (configuration.SignAssembly)
            {
                if (File.Exists(configuration.AssemblyKeyFile))
                {
                    sb.AppendFormat("\"-keyfile:{0}\"", configuration.AssemblyKeyFile);
                    sb.AppendLine();
                }
            }

            if (!string.IsNullOrEmpty(compilerparameters.DocumentationFile))
            {
                sb.AppendFormat("\"-doc:{0}\"", compilerparameters.DocumentationFile);
                sb.AppendLine();
            }

            if (!string.IsNullOrEmpty(projectparameters.StartupObject) && projectparameters.StartupObject != "Sub Main")
            {
                sb.Append("-main:");
                sb.Append(projectparameters.StartupObject);
                sb.AppendLine();
            }

            if (compilerparameters.RemoveIntegerChecks)
            {
                sb.AppendLine("-removeintchecks+");
            }

            if (!string.IsNullOrEmpty(compilerparameters.AdditionalParameters))
            {
                sb.Append(compilerparameters.AdditionalParameters);
                sb.AppendLine();
            }

            switch (configuration.CompileTarget)
            {
            case CompileTarget.Exe:
                sb.AppendLine("-target:exe");
                break;

            case CompileTarget.WinExe:
                sb.AppendLine("-target:winexe");
                break;

            case CompileTarget.Library:
                sb.AppendLine("-target:library");
                break;

            case CompileTarget.Module:
                sb.AppendLine("-target:module");
                break;

            default:
                throw new NotSupportedException("unknown compile target:" + configuration.CompileTarget);
            }

            return(sb.ToString());
        }
Beispiel #37
0
        /// <summary>
        /// تبدیل یک رشته ایران سیستم به یونیکد
        /// </summary>
        /// <param name="textEncoding">کدپیج رشته ایران سیستم</param>
        /// <param name="iranSystemEncodedString">رشته ایران سیستم</param>
        /// <returns></returns>
        public static string UnicodeFrom(TextEncoding textEncoding, string iranSystemEncodedString)
        {
            // حذف فاصله های موجود در رشته
            iranSystemEncodedString = iranSystemEncodedString.Replace(" ", "");

            /// بازگشت در صورت خالی بودن رشته
            if (string.IsNullOrWhiteSpace(iranSystemEncodedString))
            {
                return string.Empty;
            }

            // در صورتی که رشته تماماً عدد نباشد
            if (!IsNumber(iranSystemEncodedString))
            {
                /// تغییر ترتیب کاراکترها از آخر به اول
                iranSystemEncodedString = Reverse(iranSystemEncodedString);

                /// خارج کردن اعداد درون رشته
                iranSystemEncodedString = ExcludeNumbers(iranSystemEncodedString);
            }

            // وهله سازی از انکودینگ صحیح برای تبدیل رشته ایران سیستم به بایت
            Encoding encoding = Encoding.GetEncoding((int)textEncoding);

            // تبدیل رشته به بایت
            byte[] stringBytes = encoding.GetBytes(iranSystemEncodedString.Trim());

            // آرایه ای که بایت های معادل را در آن قرار می دهیم
            // مجموع تعداد بایت های رشته + بایت های اضافی محاسبه شده
            byte[] newStringBytes = new byte[stringBytes.Length + CountCharactersRequireTwoBytes(stringBytes)];

            int index = 0;

            // بررسی هر بایت و پیدا کردن بایت (های) معادل آن
            for (int i = 0; i < stringBytes.Length; ++i)
            {
                byte charByte = stringBytes[i];

                // اگر جز 128 بایت اول باشد که نیازی به تبدیل ندارد چون کد اسکی است
                if (charByte < 128)
                {
                    newStringBytes[index] = charByte;
                }
                else
                {
                    // اگر جز حروف یا اعداد بود معادلش رو قرار می دیم
                    if (CharactersMapper.ContainsKey(charByte))
                    {
                        newStringBytes[index] = CharactersMapper[charByte];
                    }
                }

                // اگر کاراکتر ایران سیستم "لا" بود چون کاراکتر متناظرش در عربی 1256 "ل" است و باید یک "ا" هم بعدش اضافه کنیم
                if (charByte == 242)
                {
                    newStringBytes[++index] = 199;
                }

                // اگر کاراکتر یکی از انواعی بود که بعدشان باید یک فاصله باشد
                // و در عین حال آخرین کاراکتر رشته نبود
                if (charactersWithSpaceAfter.Contains(charByte) && Array.IndexOf(stringBytes, charByte) != stringBytes.Length - 1)
                {
                    // یک فاصله بعد ان اضافه می کنیم
                    newStringBytes[++index] = 32;
                }

                index += 1;
            }

            // تبدیل به رشته و ارسال به فراخواننده
            byte[] unicodeContent = Encoding.Convert(encoding, Encoding.Unicode, newStringBytes);

            string convertedString = Encoding.Unicode.GetString(unicodeContent).Trim();

            return IncludeNumbers(convertedString);
        }
        public static bool ConvertFromTs(string targetFormat, string fileName, string outputFolder, bool overwrite, ref int count, ref int converted, ref int errors, List <SubtitleFormat> formats, StreamWriter stdOutWriter, CommandLineConverter.BatchConvertProgress progressCallback, Point?resolution, TextEncoding targetEncoding, List <CommandLineConverter.BatchAction> actions, TimeSpan offset, int pacCodePage, double?targetFrameRate, HashSet <string> multipleReplaceImportFiles, string ocrEngine, bool teletextOnly)
        {
            var success = false;
            var programMapTableParser = new ProgramMapTableParser();

            programMapTableParser.Parse(fileName); // get languages
            var tsParser = new TransportStreamParser();

            tsParser.Parse(fileName, (position, total) =>
            {
                var percent = (int)Math.Round(position * 100.0 / total);
                stdOutWriter?.Write("\rParsing transport stream {0}: {1}%", fileName, percent);
                progressCallback?.Invoke($"{percent}%");
            });
            stdOutWriter?.WriteLine();

            // images
            if (!teletextOnly)
            {
                foreach (int id in tsParser.SubtitlePacketIds)
                {
                    if (BatchConvert.BluRaySubtitle.RemoveChar(' ').Equals(targetFormat.RemoveChar(' '), StringComparison.OrdinalIgnoreCase))
                    {
                        TsToBluRaySup.WriteTrack(fileName, outputFolder, overwrite, count, stdOutWriter, progressCallback, resolution, programMapTableParser, id, tsParser);
                        success = true;
                    }
                    else if (BatchConvert.BdnXmlSubtitle.RemoveChar(' ').Equals(targetFormat.RemoveChar(' '), StringComparison.OrdinalIgnoreCase))
                    {
                        TsToBdnXml.WriteTrack(fileName, outputFolder, overwrite, stdOutWriter, progressCallback, resolution, programMapTableParser, id, tsParser);
                        success = true;
                    }
                    else
                    {
                        var preExt           = TsToBluRaySup.GetFileNameEnding(programMapTableParser, id);
                        var binaryParagraphs = new List <IBinaryParagraph>();
                        var subtitle         = new Subtitle();
                        foreach (var transportStreamSubtitle in tsParser.GetDvbSubtitles(id))
                        {
                            binaryParagraphs.Add(transportStreamSubtitle);
                            subtitle.Paragraphs.Add(new Paragraph(string.Empty, transportStreamSubtitle.StartMilliseconds, transportStreamSubtitle.EndMilliseconds));
                        }

                        success = CommandLineConverter.BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, subtitle, new SubRip(), binaryParagraphs, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, resolution, true, null, null, ocrEngine, preExt);
                        if (success)
                        {
                            converted--;
                        }
                    }
                }
            }

            // teletext
            foreach (var program in tsParser.TeletextSubtitlesLookup)
            {
                foreach (var kvp in program.Value)
                {
                    var subtitle = new Subtitle(kvp.Value);
                    subtitle.Renumber();
                    var preExt = TsToBluRaySup.GetFileNameEnding(programMapTableParser, kvp.Key);
                    success = CommandLineConverter.BatchConvertSave(targetFormat, offset, targetEncoding, outputFolder, count, ref converted, ref errors, formats, fileName, subtitle, new SubRip(), null, overwrite, pacCodePage, targetFrameRate, multipleReplaceImportFiles, actions, resolution, true, null, null, null, preExt);
                    if (success)
                    {
                        converted--;
                    }
                }
            }

            return(success);
        }
        public static bool TryEncode(this Utf8String value, Span<byte> buffer, out int bytesWritten, TextEncoding encoding = TextEncoding.Utf8)
        {
            if (encoding == TextEncoding.Utf16) {
                bytesWritten = 0;
                int justWritten;
                foreach(var cp in value.CodePoints) {
                    if(!Utf16.Utf16LittleEndianEncoder.TryEncodeCodePoint(cp, buffer.Slice(bytesWritten), out justWritten)) {
                        bytesWritten = 0;
                        return false;
                    }
                    bytesWritten += justWritten ;
                }
                return true;
            }

            if (encoding == TextEncoding.Utf8) {
                if (buffer.Length < value.Length) {
                    bytesWritten = 0;
                    return false;
                }

                value.Bytes.CopyTo(buffer);
                bytesWritten = value.Length;
                return true;
            }

            throw new NotImplementedException();
        }