Master sync

Some random improvements / code de-duplication. I haven't actually tested this.