I think there still are some parts worth merging in this PR. I'll try to remove the confusing bits.