Compilation cleanup and automatic library dependencies cleanup

This pullrequest is based on and replaces #1726. While rebasing that PR I also moved some code around for a more sensible structure, which again exposed some opportunities for cleanup, meaning this pullrequest now moves a lot of code around, while only the last commit actually changes the detection of dependencies.

The other commits move and clean up code, which does improve consistency in a few places, fixing a few bugs as a side effect.