improved rebuild function