Various fixes by @tomzx