Refactored chain management.

I need to comment this properly tomorrow. Should be more robust, not
sure yet.