improved layout function