Again, merging this ASAP because it works, but this could be much clearer with backrefs.