       while i < node.childNodes.length
         @cleanTree node.childNodes[i]
         if not node.childNodes[i].__location
+          if node.childNodes[i].childNodes?
+            for child in node.childNodes[i].childNodes
+              child.parentNode = node
           node.childNodes = node.childNodes[0...i].concat(node.childNodes[i].childNodes || []).concat node.childNodes[i+1...]
         else
           i++
 
-  fixBounds: (node, lastPosition) ->
+  fixBounds: (node) ->
 
     if not node
+      return
+
+    if node.childNodes?
+      for child, i in node.childNodes
+        @fixBounds child
+      newList = []
+      for child in node.childNodes
+        if !child.remove
+          newList.push child
+      node.childNodes = newList
+
+    if node.nodeName is '#document' or node.nodeName is '#document-fragment'
+      node.type = 'document'
       return
 
     if node.nodeName is '#text'

        @setAttribs node, @text[node.__location.start...node.__location.end]
      return

    if node.childNodes?
      for child, i in node.childNodes
        if i is node.childNodes.length - 1
          lastPosition = node.__location?.endTag?.start ? lastPosition
        else
          lastPosition = node.childNodes[i+1].__location.start ? lastPosition
        @fixBounds child, lastPosition
      newList = []
      for child in node.childNodes
        if !child.remove
          newList.push child
      node.childNodes = newList

    if node.nodeName is '#document' or node.nodeName is '#document-fragment'
      node.type = 'document'
      return

    node.type = 'blockTag'

    node.__indentLocation = {start: node.__location.startTag.end}

      node.__indentLocation.end = node.__location.startTag.end

    if not node.__location.endTag
      # Forcing object copy because
      # sometimes parse5 reuses location info
      # for semi-fake nodes.
      node.__location = {
        start: node.__location.start
        end: node.__indentLocation.end
      }

    @setAttribs node, @text[node.__location.start...node.__indentLocation.start]

  getEndPoint: (node) ->
    if node.nodeName in ['#document', '#document-fragment']
      return @text.length
    last = null
    parent = node.parentNode
    ind = parent.childNodes.indexOf node
    if ind is parent.childNodes.length - 1
      last = if parent.__location?.endTag? then parent.__location.endTag.start else @getEndPoint parent
    else
      last = parent.childNodes[ind+1].__location.start
    return last

  trimText: (node) ->
    location = node.__location
    location.end = Math.min location.end, @getEndPoint node
    text = @text[location.start...location.end].split '\n'
    i = 0
    while text[i].trim().length is 0
