merged improved layout algorithm into CGI version