Fix circular reference handling and cleanup a bit