improved layout logic