                     //append it to resul
                     result.append(string)
                     
-                    //remove the chunk from data
-                    data.removeSubrange(0..<index)
-                    
                     //reset index position
+                    startIndex += index
                     index = dataUnitSize
                     break
                 }
                 index += dataUnitSize
             }
         }
-        
+
+        //remove the chunk from data
+        data.removeSubrange(0 ..< startIndex)
+
         if(result == "" && data.count > MINIMUM_BUFFER_SIZE) {
             //could not find any string in the data
             throw Exception.InvalidDataEncoding(requestedEncoding: encoding, description: description)

    let bufferSize:             Int
    let dataUnitSize:           Int

    var data:                   [UInt8]
    var buffer:                 [UInt8]
    var encoding:               String.Encoding
    var firstData:              Bool

     
     - SeeAlso: https://en.wikipedia.org/wiki/Byte_order_mark
    */
    private func analyzeBOM()  throws -> Int {
        if(encoding == String.Encoding.utf16)
        {
            //need to specify utf16 encoding reading BOM
            if(buffer.starts(with: InputStreamReader.UTF16LE_BOM)) {
                encoding = String.Encoding.utf16LittleEndian
                return InputStreamReader.UTF16LE_BOM.count
            }
            else if(buffer.starts(with: InputStreamReader.UTF16BE_BOM)) {
                encoding = String.Encoding.utf16BigEndian
                return InputStreamReader.UTF16BE_BOM.count
            } else {
                throw Exception.InvalidDataEncoding(requestedEncoding: encoding, description: "\(description): UTF-16 data without BOM. Please Use UTF-16LE or UTF-16BE instead.")
            }
        } else if (encoding == String.Encoding.utf32) {
            //need to specify utf32 encoding reading BOM
            if(buffer.starts(with: InputStreamReader.UTF32LE_BOM)) {
                encoding = String.Encoding.utf32LittleEndian
                return InputStreamReader.UTF32LE_BOM.count
            }
            else if(buffer.starts(with: InputStreamReader.UTF32BE_BOM)) {
                encoding = String.Encoding.utf32BigEndian
                return InputStreamReader.UTF32BE_BOM.count
            } else {
                throw Exception.InvalidDataEncoding(requestedEncoding: encoding, description: "\(description): UTF-32 data without BOM. Please Use UTF-32LE or UTF-32BE instead.")
            }
        }
        return 0
    }
    
    /**
