twip: correctly expand entities for multiple medias

Compare the two files at https://gist.github.com/3e1c342e4f3a8173b8aa.

Note that currently the sort is unstable, which can be undesirable (it can shuffle medias). Also note that I haven't tested this code much.

Thanks.