generalize and fix select legalization code