First cut at query optimizer