added layout handle merging, refactored code