Reconstruct My Matryoshka Dolls Background

A matryoshka doll (or Russian nesting doll) is a set of dolls that fit inside of each other. I've accidentally mixed up my collection of matryoshka dolls and I don't remember which one goes inside which.

Objective

Given a list of unique strings, sort them into nested matryoshka dolls. Each string is an individual doll, and a matryoshka doll is a list of strings.

Rules

Let min(a,b) be the lexicographic min of strings a and b. Let a ⊂ b denote that a is a substring of b. Then,


The list of matryoshka dolls must be sorted lexicographically
String a can fit into string b if a ⊂ b
If a ⊂ b and a ⊂ c, then a will go inside min(b,c)
If both a ⊂ c and b ⊂ c, but a ⊄ b b ⊄ a, then only min(a,b) will go inside c
If both a ⊂ c and b ⊂ c, and also a ⊂ b, then only b will go inside c. I.e., superstrings go before substrings so that the matryoshka isn't prematurely terminated.


Examples

In:
hahaha, hah, lol, lololol, bahaha, bah, haha, ah

Out:
bahaha, bah, ah
hahaha, haha, hah
lololol, lol

In:
aa, aaaa, a, aaaaaaaaaa

Out:
aaaaaaaaaa, aaaa, aa, a
Python 2, 298 bytes



def f(x,E=enumerate):
 o=[]
 while any(x):
&#9;for k,p in E(x):
&#9; e=0
&#9; if sum(i(p,j)for j in x)&lt;1:
&#9;&#9;for d,r in E(o):
&#9;&#9; if i(p,r[-1])*((r[-1]&lt;e)or e==0):m,e=d,r[-1]
&#9;&#9;if e:o[m]+=[p]
&#9;&#9;else:o+=[[p]]
&#9;&#9;x[k]=''
 print sorted(o)
i=lambda p,b:(b!=p)*any([p==b[j:j+len(p)]for j in range(len(b)-len(p)+1)])


Try it online!

-28 bytes with tips from @dylnan, bug find by @Dennis, and bug fix by @Mr.Xcoder