Misc fixes and optimizations.
Fix sorting by depth.