refactor layer control code into function