Updated debug to detect circular references.
Refactored debug to be easier to maintain.