Added removeReferences() function. Used before the recursive call