rewrite of ThresholdTwoLevels (rebased to current master)