Maybe this should be a separate method. The code has become a bit too complex to be inlined IMO.