copied layout preservation algorithm for debugging purposes