def nest_toc_tokens(toc_list):
 ordered_list = []
 if len(toc_list):
  last = toc_list.pop(0)
  last[u'children'] = []
  levels = [last[u'level']]
  ordered_list.append(last)
  parents = []
  while toc_list:
   t = toc_list.pop(0)
   current_level = t[u'level']
   t[u'children'] = []
   if (current_level < levels[(-1)]):
    levels.pop()
    to_pop = 0
    for p in reversed(parents):
     if (current_level <= p[u'level']):
      to_pop += 1
     else:
      break
    if to_pop:
     levels = levels[:(- to_pop)]
     parents = parents[:(- to_pop)]
    levels.append(current_level)
   if (current_level == levels[(-1)]):
    (parents[(-1)][u'children'] if parents else ordered_list).append(t)
   else:
    last[u'children'].append(t)
    parents.append(last)
    levels.append(current_level)
   last = t
 return ordered_list

def nest_toc_tokens ( toc_list ) : ordered_list = [ ] if len ( toc_list ) : last = toc_list . pop ( 0 ) last [ u'children' ] = [ ] levels = [ last [ u'level' ] ] ordered_list . append ( last ) parents = [ ] while toc_list : t = toc_list . pop ( 0 ) current_level = t [ u'level' ] t [ u'children' ] = [ ] if ( current_level < levels [ ( - 1 ) ] ) : levels . pop ( ) to_pop = 0 for p in reversed ( parents ) : if ( current_level <= p [ u'level' ] ) : to_pop += 1 else : break if to_pop : levels = levels [ : ( - to_pop ) ] parents = parents [ : ( - to_pop ) ] levels . append ( current_level ) if ( current_level == levels [ ( - 1 ) ] ) : ( parents [ ( - 1 ) ] [ u'children' ] if parents else ordered_list ) . append ( t ) else : last [ u'children' ] . append ( t ) parents . append ( last ) levels . append ( current_level ) last = t return ordered_list
given an unsorted list with errors and skips .