Move layer tree code out to separate file, add some more fixes to it and clean up after merge.