ported changed from master