The code is using a lot of `insert`, which is making it quite tricky to follow. It should be possible to make this function simpler.