/// <summary>
        ///   <p>Decodes given set of received codewords, which include both data and error-correction
        /// codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
        /// in the input.</p>
        /// </summary>
        /// <param name="received">data and error-correction codewords</param>
        /// <param name="twoS">number of error-correction codewords available</param>
        /// <returns>false: decoding fails</returns>
        public bool Decode(int[] received, int twoS)
        {
            var poly = new GenericGFPoly(field, received);
            var syndromeCoefficients = new int[twoS];
            var noError = true;

            for (var i = 0; i < twoS; i++)
            {
                int eval = poly.EvaluateAt(field.Exp(i + field.GeneratorBase));
                syndromeCoefficients[syndromeCoefficients.Length - 1 - i] = eval;
                if (eval != 0)
                {
                    noError = false;
                }
            }

            if (noError)
            {
                return(true);
            }

            var syndrome = new GenericGFPoly(field, syndromeCoefficients);

            GenericGFPoly[] sigmaOmega = RunEuclideanAlgorithm(field.BuildMonomial(twoS, 1), syndrome, twoS);
            if (sigmaOmega == null)
            {
                return(false);
            }

            GenericGFPoly sigma = sigmaOmega[0];

            int[] errorLocations = FindErrorLocations(sigma);

            if (errorLocations == null)
            {
                return(false);
            }

            GenericGFPoly omega = sigmaOmega[1];

            int[] errorMagnitudes = FindErrorMagnitudes(omega, errorLocations);

            for (int i = 0; i < errorLocations.Length; i++)
            {
                int position = received.Length - 1 - field.Log(errorLocations[i]);
                if (position < 0)
                {
                    // throw new ReedSolomonException("Bad error location");
                    return(false);
                }
                received[position] = GenericGF.AddOrSubtract(received[position], errorMagnitudes[i]);
            }

            return(true);
        }
        private GenericGFPoly BuildGenerator(int degree)
        {
            if (degree >= cachedGenerators.Count)
            {
                GenericGFPoly lastGenerator = cachedGenerators[cachedGenerators.Count - 1];

                for (int d = cachedGenerators.Count; d <= degree; d++)
                {
                    var nextGenerator = lastGenerator.Multiply(new GenericGFPoly(field, new int[] { 1, field.Exp(d - 1 + field.GeneratorBase) }));
                    cachedGenerators.Add(nextGenerator);
                    lastGenerator = nextGenerator;
                }
            }

            return(cachedGenerators[degree]);
        }