add cycle detection, clean up