cleaned and optimized layout.c