Move code closer to upstream.

I have made many cosmetical changes so that we get close to upstream,
and I have merged some code back from upstream to here.

The downside is that there were some improvements which have never
made it to upstream, and now those are lost. Sorry, I just don't have
the time to properly search and merge them now.

Judging from the code, the workarounds that have been decimated now
used to do something about selections where one of the ends is touching
an image. So if we start seeing errors about juch selections, we should
come back here, and try to resurrect some of this code.