major improvements to layout algorithm