Fixed bugs in reorganized layout code