translatr.CineFile.blockChangeSub C# (CSharp) Method

blockChangeSub() private method

private blockChangeSub ( byte array, SubtitleEntry entry, int blockno ) : byte[]
array byte
entry SubtitleEntry
blockno int
return byte[]
        private byte[] blockChangeSub(byte[] array, SubtitleEntry entry, int blockno)
        {
            int index = array.Length - 1;
            byte[] output = null;

            // Remove end zeros
            while (index >= 0 && array[index] == 0x00)
            {
                index--;
            }

            int endidx = index;
            int startidx = findSubsStartIndex(array, endidx);
            if (startidx == 0)
                throw new Exception("Error finding sub to replace");

            // Read original subs
            List<SubtitleEntry> origSubs = new List<SubtitleEntry>();
            parseSubsBlock(origSubs, Encoding.UTF8.GetString(array, startidx + 4, endidx - startidx - 4), blockno);

            // Replace new subtitle text
            foreach (SubtitleEntry newEntry in subEntries)
            {
                if (newEntry.blockNumber != blockno)
                    continue;

                foreach (SubtitleEntry origEntry in origSubs)
                {
                    if (newEntry.lang == origEntry.lang)
                    {
                        origEntry.text = newEntry.text;
                        break;
                    }
                }
            }

            // Get the modified subs block
            var subs = rebuildSubsBlock(origSubs, blockno); //origSubs being the new subs

            // Compute total length
            int length = startidx + subs.Length;
            // Align to 16 bytes
            length = ((length + 15) >> 4) << 4;

            output = new byte[length];

            // Copy data before subs
            Array.Copy(array, output, startidx);

            // Copy subs
            Array.Copy(subs, 0, output, startidx, subs.Length);

            // Adjust lengths
            MemoryStream ms = new MemoryStream(output);
            ms.Position = 4;
            ms.writeuint((uint)(length - 16), isBE);
            if (blockno != 0)
            {
                ms.Position = 16;
                ms.writeuint((uint)(length - 20), isBE);
            }

            return output;
        }