factor out dump() function, handle reference loops