Refactor gate code to use common functions of AND and OR.