major rewrite of optimizer